Rails:我如何建模偏好? 我应该使用has_many:through吗?

我有两个模型:User和HairColor。 用户只有一种头发颜色,但可以有许多头发颜色首选项。 对此进行建模的最佳方法是什么?

这是我开始做的事情:

#models/user.rb class User  :preferences end #models/hair_color.rb class HairColor < ActiveRecord::Base has_many :users end #models/preference.rb class Preference < ActiveRecord::Base belongs_to :user belongs_to :hair_color end 

使用has_many:通过正确的方法? 如果我想将其扩展到其他属性,如“眼睛颜色”,该怎么办? (用户有一种眼睛颜色,但可能更喜欢许多眼睛颜色“

头发颜色会有限,因此首选项表需要有hair_color_id并设置如下:

 #models/user.rb class User < ActiveRecord::Base has_one :hair_color has_many :preferences end #models/hair_color.rb class HairColor < ActiveRecord::Base belongs_to :user belongs_to :preference end #models/preference.rb class Preference < ActiveRecord::Base belongs_to :user has_many :hair_color end 

我相信这是对的。 如果你遇到任何障碍,请告诉我。


当你添加眼睛颜色或任何其他特征时,你可能不得不做一些不同的偏好。 那时我有4列: id, user_id, foreign_id, foreign_type

foreign_id将是eye_color / hair_color表中的id,而foreign_type将是“eye”或“hair”或其他东西。 然后在你的模型中,你会有这样的事情:

 #models/hair_color.rb class HairColor < ActiveRecord::Base belongs_to :user has_many :preferences, :foreign_key => :foreign_id, :conditions => { "preferences.foreign_type" => "hair" } end 

这有点疯狂,但这是最干的方式。 你在eye_color.rb中添加了相同的东西,只需用foreign_type替换“eye”和“eye”。