在控制器方法中分配给模型没有任何作用

问题描述 投票:0回答:1

我想在将其保存到处理 POST 请求的

Item
create
方法中之前为我的
ItemsController
模型赋值。但好像什么也没发生。

# 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

为什么

@item.user_id
@item.list_id
在作业刚完成后仍然显示为
nil

ruby-on-rails ruby
1个回答
1
投票

删除这个:

attr_accessor :list_id, :user_id # this should allow me to assign to fields directly

您已经可以默认分配

list_id
user_id
。 Rails 为您使用自己的属性访问器覆盖的表中的每一列创建读取器和写入器。属性背后的逻辑比简单的实例变量赋值要多得多。

© www.soinside.com 2019 - 2024. All rights reserved.