Rails 多个所属的分配 [英] Rails multiple belongs_to assignment
问题描述
给定
用户:
class User < ActiveRecord::Base
has_many :discussions
has_many :posts
end
讨论:
class Discussion < ActiveRecord::Base
belongs_to :user
has_many :posts
end
帖子:
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :discussion
end
我目前正在通过
@post = current_user.posts.build(params[:post])
我的问题是,如何设置/保存/编辑@post 模型,以便同时设置帖子和讨论之间的关系?
My question is, how do I set/save/edit the @post model such that the relationship between the post and the discussion is also set?
推荐答案
保存和编辑讨论以及帖子
现有讨论
要将您正在构建的帖子与现有讨论相关联,只需将 id 合并到帖子参数中
To associate the post you're building with an existing discussion, just merge the id into the post params
@post = current_user.posts.build(
params[:post].merge(
:discussion_id => existing_discussion.id
)
您必须在 @post
的表单中为讨论 id 设置一个隐藏输入,以便保存关联.
You will have to have a hidden input for discussion id in the form for @post
so the association gets saved.
新讨论
如果您想与每个帖子一起构建新讨论并通过表单管理其属性,请使用 accepts_nested_attributes
If you want to build a new discussion along with every post and manage its attributes via the form, use accepts_nested_attributes
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :discussion
accepts_nested_attributes_for :discussion
end
您必须在构建帖子后使用 build_discussion
在控制器中构建讨论
You then have to build the discussion in the controller with build_discussion
after you built the post
@post.build_discussion
并且在您的表单中,您可以包含用于讨论的嵌套字段
And in your form, you can include nested fields for discussions
form_for @post do |f|
f.fields_for :discussion do |df|
...etc
这将与帖子一起创建讨论.有关嵌套属性的更多信息,观看这个精彩的 railscast
此外,您可以使用 has_many
关联,以获得更一致的关系设置:
Furthermore, you can use the :through
option of the has_many
association for a more consistent relational setup:
class User < ActiveRecord::Base
has_many :posts
has_many :discussions, :through => :posts, :source => :discussion
end
class Discussion < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :discussion
end
这样,用户与讨论的关系只在Post
模型中维护,而不是在两个地方.
Like this, the relation of the user to the discussion is maintained only in the Post
model, and not in two places.
这篇关于Rails 多个所属的分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!