【问题标题】:Rails nested models and virtual attribute initializationRails 嵌套模型和虚拟属性初始化
【发布时间】:2016-01-27 17:04:20
【问题描述】:

我无法理解如何将属性“发送”到嵌套模型,以及是否也可以对具有虚拟属性的模型执行此操作。我有三个模型:

class User < ActiveRecord::Base
   ...
   has_and_belongs_to_many :clearancegoods
   has_many :clearanceitems, through: :user_clearanceitems_descriptions
   has_many :user_clearanceitems_descriptions
   ...
end

class Clearanceitem < ActiveRecord::Base
    ...
    has_many :users, through: :user_clearanceitems_descriptions
    has_many :user_clearanceitems_descriptions
    accepts_nested_attributes_for :user_clearanceitems_descriptions
    ...
    def user_id
        @user_id
    end
    def user_id=(val)
        @user_id = val
    end
end

class UserClearanceitemsDescription < ActiveRecord::Base
    belongs_to :user
    belongs_to :clearanceitem
end

在控制台中:

desc = User.find(5).user_clearanceitems_descriptions.new
desc.user_id 
### result is 5

item = User.find(5).clearanceitems.new
item.user_id
### result in nil

【问题讨论】:

  • 你应该澄清你想要通过添加的 user_id 属性来完成什么。

标签: ruby-on-rails associations nested-attributes rails-models virtual-attribute


【解决方案1】:

如果 Clearanceitem 可以有多个用户,那么它不能有一个 user_id,否则该属性必须有多个值。如果您只是想创建与用户关联的 Clearanceitems,ActiveRecord 将自动创建关联的加入记录:

User.find(5).clearanceitems.create
User.find(5).clearanceitems # Contains the Clearanceitem you just created

所以只需从Clearanceitem 中删除user_id 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2011-03-11
    • 2013-12-16
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多