ruby - Rails 多个 belongs_to 赋值

标签 ruby ruby-on-rails-3 belongs-to

给定

用户:

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/

相关文章:

ruby - 在非常复杂的 Ruby 应用程序中查找内存泄漏

ruby-on-rails - 如何在 Rails 2.0 中制作下拉列表?

ruby-on-rails - 地理编码器 gem 的 country_code 列表

ruby-on-rails - Rails 3.2 从 subview 创建父模型

ruby-on-rails - 按 belongs_to 自定义 foreign_key 搜索

javascript - 如何根据两个选择器查找元素?

ruby - RAM 内存不足

ruby-on-rails - 如何验证关联的模型 ID?

ruby-on-rails-3 - 将 best_in_place 与 TinyMCE 等富文本编辑器一起使用

database - 无法删除不在表中的 Nil 数据