给定
用户:
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
我目前正在通过
在 Controller 中初始化 Posts@post = current_user.posts.build(params[:post])
我的问题是,如何设置/保存/编辑@post 模型,以便同时设置帖子和讨论之间的关系?
最佳答案
保存和编辑讨论以及帖子
现有讨论
要将您正在构建的帖子与现有讨论相关联,只需将 id 合并到帖子参数中
@post = current_user.posts.build(
params[:post].merge(
:discussion_id => existing_discussion.id
)
您必须在 @post
的表单中为讨论 ID 隐藏输入,以便保存关联。
新讨论
如果您想在每个帖子中建立一个新讨论并通过表单管理其属性,请使用 accepts_nested_attributes
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :discussion
accepts_nested_attributes_for :discussion
end
然后,您必须在构建帖子后使用 build_discussion
在 Controller 中构建讨论
@post.build_discussion
并且在您的表单中,您可以包含用于讨论的嵌套字段
form_for @post do |f|
f.fields_for :discussion do |df|
...etc
这将与帖子一起创建讨论。有关嵌套属性的更多信息,watch this excellent railscast
更好的关系
此外,您可以使用 has_many
association 的 :through
选项为了更一致的关系设置:
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
模型中维护,而不是在两个地方。
关于ruby - Rails 多个 belongs_to 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11539151/