繁体   English   中英

Rails中的多个belongs_to模型

[英]multiple belongs_to models in Rails

我有一个评论模型,目前正在与Articles一起使用。 我现在希望用户能够对Coffeeshop的评论发表评论。 我是否可以使用相同的注释表,还是应该有一个单独的注释表(感觉简陋)? 我使用RoR的时间不长(几周),因此仍然尝试掌握基本知识。

我会把它们嵌套在routes.rb中吗?

  resources :coffeeshops do
  resources :articles do
    resources :comments
  end

要么

  resources :coffeeshops do
    resources :comments
  end

  resources :articles do
    resources :comments
  end

我的模型如下:

用户

class User < ApplicationRecord
has_many :comments
end

评论

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :article
  belongs_to :coffeeshop
end

文章

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end

咖啡店

class Coffeeshop < ApplicationRecord
has_many :comments, dependent: :destroy

然后,假设我需要一个外键来将用户和评论绑定在一起,然后再将评论添加到文章/咖啡店。

我会使用多态关联。

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class User < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :commentable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable
end

class Coffeeshop < ApplicationRecord
  has_many :comments, as: :commentable
end

有关设置路由/控制器的更多信息:

https://rubyplus.com/articles/3901-Polymorphic-Association-in-Rails-5 http://karimbutt.github.io/blog/2015/01/03/step-by-step-guide-to-polymorphic -铁路协会/

您可以对文章和咖啡店的注释都使用注释模型,但是(因为默认情况下,rails使用id作为主键和外键,所以我也假设您也使用id),因此您必须在注释表中添加列,在其中设置注释类型(您可以在注释模型中创建枚举器,在其中设置2种可能的值类型,每种类型分别用于商品和咖啡店模型。 如果不添加此列,将导致奇怪,难以跟踪的错误,您可以在其中看到具有相同ID的咖啡店文章评论,反之亦然。

UPD:他对在Rails模型中使用枚举没有什么指导:http://www.justinweiss.com/articles/creating-easy-可读-attributes-with-activerecord-enums /您将不得不在实际的添加评论表格中使用它,但在幕后。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM