我有一个表单,它使用accepts_nested_attributes_for
创建一个新的子记录和一个新的父记录。
child 和家长有一个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
因为我正在操作 Controller 中的一些数据来确定 schedule
保存之前的对象。
关于堆栈溢出有很多答案可以使用预先存在的父记录来完成此操作,但对于以前不存在任何关联的情况,我无法找到任何答案。
我尝试使用 after_create
来做到这一点模型中的回调但无权访问 params
并且已经了解到无论如何这样做都是不好的程序。 (Rails How to pass params from controller to after_save inside model)。
理想情况下我想设置 schedule
在创建关系记录以及 child_id
的同一个数据库调用中和parent_id
.
对此的任何帮助都会很棒,谢谢
更新
截至原始帖子的 Controller
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
parent
使用 Ryan Bates' nested form helper 构建。这是它的构建线:
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
...
end
end
我不是在构建relationship
无论如何,据我所知,它是由 Rails 神奇地构建的。
尝试Danny Van Hoof的建议 @child.relationships[0].schedule =
我得到undefined method schedule=' for nil:NilClass
因为不存在任何关系。
如果我事先在 new
中建立关系或create
使用 @child.relationship.build
的操作我保存了 2 条关系记录:
我构建的有 schedule
已保存但没有parent_id
(家长组 ID)
第二条记录是神奇地构建的,并且有两个正确的 ID,但没有 schedule
.
现在,当尝试Rick Peck的建议时,添加
def params
params.require(:child).permit(relationships_attributes: [:schedule])
# tried with and without `parents_attributes`
end
我得到一个stack level too deep
params.require
上的错误线。我也不完全明白这是做什么的。 (我对 Rails 还很陌生)
感谢您的帮助!
最佳答案
我的一个网站有一个与你类似的结构,它工作正常,除了我(翻译成你的例子)有
attr_accessible :relationships_attributes
accepts_nested_attributes_for :relationships, allow_destroy: true
在我的关系模型中,我使parent_id可访问
这允许在 Controller 中执行类似的操作
@child.relationships[0].schedule = ...
甚至在拯救 child 之前
或者,在输入家长详细信息时立即从您的 View 中设置时间表
如果不清楚,请给我评论!
关于ruby-on-rails - 如何将属性保存到 has_many :through join table with no existing records to build from,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20295658/