代码之家  ›  专栏  ›  技术社区  ›  Meknassih

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

  •  0
  • Meknassih  · 技术社区  · 1 年前

    我想为我的 Item 模型,然后将其保存在 create 我的方法 ItemsController 处理POST请求。但似乎什么都没发生。

    # 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 任务刚结束?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Alex    1 年前

    删除此:

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

    您已经可以分配 list_id user_id 默认情况下。Rails为表中的每一列创建读写器,这些列是用自己的属性访问器覆盖的。与简单的实例变量赋值相比,属性背后有更多的逻辑。