【发布时间】:2014-01-08 02:19:32
【问题描述】:
我似乎无法弄清楚如何在没有活动会话的情况下自动创建 has_many through 记录。
我有两个通过 family_association 模型相关的模型:
class Tree < ActiveRecord::Base
has_many :family_associations
has_many :families, through: :family_associations
end
class Family < ActiveRecord::Base
has_many :family_associations
has_many :trees, through: :family_associations
end
在我的 Show Tree 视图中,有一个按钮可以创建一个新 Family 并将 Tree 的 id 作为 url 参数传递
<%= link_to "Add Family to Tree", new_family_path(:tree_id=>@tree.id), :class => "btn btn-default" %>
仅供参考:我不能拥有 Family belongs_to Tree 模型,因为理论上我选择的家庭将来属于多棵树。因此,新的 Family 表单上没有可预填充的 tree_id 字段。
目标是在家庭记录保存后创建家庭关联记录。到目前为止,我已经创建了 associate_family 辅助方法:
def associate_family(tree, family)
FamilyAssociation.create(:tree_id => tree, :family_id => family)
end
并在我的 Family 控制器的 Create 方法中包含以下逻辑:
if @family.save
associate_family(params[:tree_id], @family.id)
关联记录已创建,但不出所料,缺少 tree_id。我会以正确的方式解决这个问题吗?有什么办法可以临时将tree_id url参数从New带到Create?
【问题讨论】:
标签: ruby-on-rails