简体   繁体   English

虽然在has_many中强制执行模型的唯一性

[英]Enforcing uniqueness of a model in has_many though

I have a User model, which has_many Dish through Recommendation . 我有一个User模型,它具有通过Recommendation Dish I would like to enforce uniqueness of Dish , as well as uniqueness of Recommendation . 我想强制执行Dish唯一性以及Recommendation唯一性。

How should I go about this in ActiveRecord ? 我应该如何在ActiveRecord这个问题?

In my dish.rb : 在我的dish.rb

validate_uniqueness_of :dish_name

What I would like to have is: when an user recommends a dish, create a new dish if it does not exist, then create recommendation. 我想拥有的是:当用户推荐菜肴时,如果不存在则创建一个新菜肴,然后创建推荐。 If the dish already exists, then just create recommendation and point to existing dish. 如果该菜已经存在,则只需创建推荐并指向现有菜。

Do I need to handle these situations manually (ie, checking existence of dish in controller), or ActiveRecord has a way to handle it internally? 我是否需要手动处理这些情况(即检查控制器中是否有dish ),或者ActiveRecord有内部处理它的方法?

Update: validate_uniqueness_of :dish_name only checks and return error message if the dish was created there. 更新: validate_uniqueness_of :dish_name仅检查并返回错误消息(如果在此创建了dish )。 It probably won't create new recommendation that points to existing dish . 它可能不会创建指向现有dishrecommendation

您总是可以.find_or_create_by_<attribute>找到开始的菜

As I see, more than one user can recommend the same dish. 如我所见,一个以上的用户可以推荐同一道菜。

Your models should look like: 您的模型应如下所示:

Class User < ActiveRecord::Base
has_many :recommendations
has_many :dishes, :through => :recommendations
end

Class Dish < ActiveRecord::Base
has_many :recommendations
has_many :users, :through => :recommendations
end

So your Recommendations table in database should have two columns (beside it's id and timestamps) called user_id and dish_id . 因此,数据库中的Recommendations表应该有两列(在ID和时间戳旁边),分别为user_iddish_id To validate that a user doesn't recommend the same dish twice, do: 要验证用户不会两次推荐相同的菜肴,请执行以下操作:

Class Recommendations < ActiveRecord::Base
belongs_to :dish
belongs_to :user
validates_uniqueness_of :dish_id, :scope => :user_id
end

And i didn't know about the .find_or_create_by method that Dan recommended, so definetly try to use something like that. 而且我不知道Dan建议的.find_or_create_by方法,因此一定要尝试使用类似的方法。

Hope i helped :) 希望我有所帮助:)

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

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