Ruby on rails 嵌套属性和通过控制器添加属性?
因为这个问题很难描述,这是我能想到的最好的标题,所以这里有一些代码 给出了三种模型:父、子和孙Ruby on rails 嵌套属性和通过控制器添加属性?,ruby-on-rails,nested-attributes,Ruby On Rails,Nested Attributes,因为这个问题很难描述,这是我能想到的最好的标题,所以这里有一些代码 给出了三种模型:父、子和孙 Parent < ActiveRecord::Base has_many :children has_many :grandchildren accepts_nested_attributes_for :child end Child < ActiveRecord::Base belongs_to :parent has_many :kids, :as =>
Parent < ActiveRecord::Base
has_many :children
has_many :grandchildren
accepts_nested_attributes_for :child
end
Child < ActiveRecord::Base
belongs_to :parent
has_many :kids, :as => :grandchildren #this is just an example
accepts_nested_attributes_for :grandchild
end
Grandchild < ActiveRecord::Base
belongs_to :parent
belongs_to :child
end
Parent:孙子女#这只是一个例子
接受:孙子的\u嵌套的\u属性\u
结束
孙子
我想将当前的_user.id添加到在父#新建期间在中创建的子记录和孙子记录中。我现在已经使用了隐藏字段,因为我找不到添加它们的好方法
也许有人可以通过创建回调来帮助您在创建时添加当前的_user.id?不管怎么说,我从来没有这么幸运地把它应用到模特身上,但你很聪明。
想法?好吧,首先,我推荐一个
有很多:从父母到孙子(通过孩子)的关系,反之亦然。有关更多详细信息,请参阅中的“关联联接模型”部分
至于你的主要问题,就像你说的,回调可能是你想要的。我认为这样的东西应该可以做到(尽管这是未经测试的代码):
有几个风格点可以做不同的事情。例如,您可以定义一个“后代”方法,该方法返回子类+孙子类并对其进行迭代,或者您可以在子类和孙子类上实现回调(在这种情况下,您可能希望将其拉入一个模块以获得最大的干度,但对于仅两个类中的单行方法,这可能是过度杀戮)。根据您想要更新当前用户的确切时间,您可能希望在保存之前使用,或者在创建之前使用其他回调而不是——您可以在中找到可用回调的完整列表。我想也可以覆盖默认的保存代码>方法
class Parent < ActiveRecord::Base
def save!
children.each { |c| c.current_user = @current_user }
grandchildren.each { |gc| gc.current_user = @current_user }
super
end
end
类父级
也未经测试。我不确定这是否可行…我会确定地检查一下。感谢您的全面介绍,尽管我对回调很熟悉,而且我的示例也不在脑子里,但这些信息将有助于以后的其他人。当我进行测试时,我会将其标记为完成,因为它看起来应该可以工作。传递@current_user没有做任何事情,但是我只是从self.user_id
中为每个子体窃取了user_id列。如果您想将答案添加到其中,我想将您的答案标记为完整。有人可以更新rails 3的响应吗?
class Parent < ActiveRecord::Base
def save!
children.each { |c| c.current_user = @current_user }
grandchildren.each { |gc| gc.current_user = @current_user }
super
end
end