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

时间:2010-12-10 15:05:14

标签: ruby-on-rails model associations relationship

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

这就是我开始做的事情:

#models/user.rb
class User < ActiveRecord::Base
  belongs_to :hair_color
  has_many :preferences, 
  has_many :hair_colors, :through => :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:通过正确的方法吗?如果我想将其扩展到其他属性,如“眼睛颜色”,该怎么办? (用户有一种眼睛颜色,但可能更喜欢许多眼睛颜色“

1 个答案:

答案 0 :(得分:1)

头发颜色数量有限,因此首选项表格需要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中,只需用“eye”替换“hair”作为foreign_type。