加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – Rails mulitple belongs_to作业

发布时间:2020-12-16 22:02:54 所属栏目:百科 来源:网络整理
导读:特定 用户: class User ActiveRecord::Base has_many :discussions has_many :postsend 讨论: class Discussion ActiveRecord::Base belongs_to :user has_many :postsend 帖子: class Post ActiveRecord::Base belongs_to :user belongs_to :discussion
特定

用户:

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模型,以便同时设置帖子和讨论之间的关系?

解决方法

保存和编辑讨论以及帖子

现有讨论

要将您正在构建的帖子与现有讨论相关联,请将该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中在控制器中构建讨论

@post.build_discussion

在您的表单中,您可以包括嵌套字段进行讨论

form_for @post do |f|
  f.fields_for :discussion do |df|
    ...etc

这将与帖子一起进行讨论.更多关于嵌套属性,watch this excellent railscast

更好的关系

此外,您可以使用has_many association的:通过选项进行更一致的关系设置:

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模型中维护,而不是在两个地方.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读