【问题标题】:Rails -- how to structure belongs_to/has_many associations?Rails——如何构建belongs_to/has_many 关联?
【发布时间】:2013-12-25 05:46:07
【问题描述】:

很简单的问题,我想:所以我有一个User 模型、一个Product 模型和一个Comment 模型。我希望用户能够对特定产品发表评论(例如对产品发表评论)。

这是正确的结构吗?

User
  has_many :comments

Product
  has_many :comments

Comment
  belongs_to :user
  belongs_to :product

谢谢。

【问题讨论】:

  • 我认为这是正确的。

标签: ruby-on-rails


【解决方案1】:

是的,如果你只想评论产品是正确的,如果你要评论产品以外的其他模型,那么使用多态关联。

如果产品被销毁或者用户被销毁,也不要忘记添加dependent: :destroy销毁相关的cmets

在产品和用户模型中添加dependent: :destroy

has_many :comments, dependent: :destroy

如果您想要除此之外的其他行为,还有其他选项,来自 Doc:

:依赖

控制当关联对象的所有者是 销毁:

:destroy causes all the associated objects to also be destroyed
:delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not execute)
:nullify causes the foreign keys to be set to NULL. Callbacks are not executed.
:restrict_with_exception causes an exception to be raised if there are any associated records
:restrict_with_error causes an error to be added to the owner if there are any associated object

【讨论】:

  • 请注意,检查数据库的保留字,例如,您可能不希望在 Oracle 下有一个名为 cmets 的表(请参阅apidock.com/rails/ActiveRecord/Base/table_name/class
  • @dosadnizub 老实说我对此一无所知,但对于这个例子,我认为大多数 Rails 开发人员使用 mysql、postgres、sqlite ......并且大多数数据库提供商都允许使用“cmets” ,所以我不确定为什么甲骨文是例外!第二件事,您的链接没有解释这一点,它解释了 table_name !!!
  • 这只是一个关于如何为模型类使用不同表名的链接 :) 避免对列和表使用保留字通常是一种好习惯,注释至少保留在一个 DB 下,以便寻找
  • 问题:如果评论只是belonged_to 一个用户,那么我可以通过@comment = user.comments.build(content: "Lorem ipsum") 实例化评论。但是,如果评论属于两个模型(UserProduct),我该怎么做?我应该使用:@comment = product.comments.build(content: "Lorem ipsum", user_id: user.id)
  • 是的,您可以执行此 product.cmets.build(content: "lorem ipsum", user_id: user.id),但我认为如果您使用的是表单,则应通过批量分配进行设置,例如在rails 3中你可以做类似product.cmets.build(params[:product]) 然后你设置@comment.user = current_user,在rails 4中这是相同的步骤但只是params [:product]应该是params .require(:comment).permit(:content)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多