I want to assign values to my Item model right before saving it in the create method of my ItemsController that handles POST requests. But it seems like nothing happens.
# app/models/item.rb
class Item < ApplicationRecord
belongs_to :user
belongs_to :list
...
attr_accessor :list_id, :user_id # this should allow me to assign to fields directly
end
# app/controllers/items_controller.rb
# POST /items or /items.json
def create
@item = Item.new(item_params) # Original generated code
@item.list_id = 1 # I am assigning a value here
@item.user_id = session[:user_id] # and here
logger.debug session[:user_id] # => 1
logger.debug @item # => #<Item id: nil, name: "sad", quantity: 1, user_id: nil, list_id: nil, created_at: nil, updated_at: nil>
...
end
Why are @item.user_id and @item.list_id still showing up as nil just after the assignment?
>Solution :
Remove this:
attr_accessor :list_id, :user_id # this should allow me to assign to fields directly
You can already assign list_id and user_id by default. Rails creates readers and writers for every column in your tables which you’re overwriting with your own attribute accessors. There is a lot more logic behind attributes than a simple instance variable assignment.