我有一个表单,可以使用以下命令创建新的子记录和新的父记录accepts_nested_attributes_for
孩子和家长都有一个has_many :through
像这样的关联:
class Child < ActiveRecord::Base
has_many :relationships
has_many :parents, through: :relationships
accepts_nested_attributes_for :parents
accepts_nested_attributes_for :relationships, allow_destroy: true
end
class Parent < ActiveRecord::Base
has_many :relationships
has_many :children, through: :relationships
end
class Relationship < ActiveRecord::Base
belongs_to :child
belongs_to :parent
accepts_nested_attributes_for :parents
#has :schedule attribute
end
我想设置schedule
属性同时存在于关系中并且不能使用accepts_nested_attributes_for
因为我正在操纵控制器中的一些数据来确定schedule
保存之前的对象。
关于堆栈溢出,有很多答案可以使用预先存在的父记录来完成此操作,但对于以前不存在任何关联的情况,我很难找到任何答案。
我尝试用after_create
模型中的回调但无权访问params
并且已经了解到无论如何这样做都是不好的程序。 (Rails 如何将参数从控制器传递到模型内的 after_save https://stackoverflow.com/questions/4725185/rails-how-to-pass-params-from-controller-to-after-save-inside-model).
理想情况下我想设置schedule
在创建关系记录的同一个数据库调用中child_id
and parent_id
.
对此的任何帮助都会很棒,谢谢
UPDATE
截至原始职位的控制器
def new
@child = Child.new
end
def create
@child = Child.new(params[:child])
schedule = build_schedule(params)
# Need to save schedule to @child.relationship[0].schedule somehow
if @child.save!
redirect_to admins_path
else
render 'new'
end
end
private
def build_schedule(params)
# works with params[:mon, :tue, :wed, :thu, :fri] to return a schedule object.
end
The parent
是使用构建的Ryan Bates 的嵌套表单助手 http://railscasts.com/episodes/196-nested-model-form-revised?view=comments。这是它的构建线:
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
...
end
end
我不是在建造relationship
无论如何,据我所知,它是由 Rails 神奇地构建的。
Trying 丹尼·范霍夫建议@child.relationships[0].schedule =
i get undefined method schedule=' for nil:NilClass
因为不存在任何关系。
如果我事先建立关系new
or create
行动使用@child.relationship.build
我保存了 2 条关系记录:
我建造的那个有schedule
已保存但没有parent_id
(家长组 ID)
第二条记录是神奇地构建的,并且具有正确的 id,但没有schedule
.
现在当尝试时里克·佩克的建议通过添加
def params
params.require(:child).permit(relationships_attributes: [:schedule])
# tried with and without `parents_attributes`
end
I get a stack level too deep
上的错误params.require
线。我也不完全明白这是做什么的。 (我对 Rails 还很陌生)
感谢您的帮助!