Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning to model in controller method does nothing

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading