扶手:我如何模型$ P ​​$ pferences?我应该使用的has_many:通过? [英] Rails: How do I model preferences? Should I use has_many :through?

查看:200
本文介绍了扶手:我如何模型$ P ​​$ pferences?我应该使用的has_many:通过?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模式:用户和染发。用户只有一根头发的颜色,但可以有许多头发的颜色preferences。什么是这个模型的最佳方法是什么?

I have two models: User and HairColor. A user has only one hair color, but can have many hair color preferences. What's the best way to model this?

这就是我开始做的:

#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:通过正确的方法?另外,如果我想要的这个扩展到其他属性,如睛彩? (A用户有一个眼睛的颜色,但可以preFER许多眼睛的颜色

Is using has_many :through the right approach? Also what if I want to extend this to other attributes such as "eye color"? (A user has one eye color, but can prefer many eye colors"

推荐答案

有将发色数量有限,所以preference表需要有一个 hair_color_id 键,设置像这样:

There will be a limited amount of hair colors, so the preference table needs to have a hair_color_id and be set up like so:

#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

我相信这是正确的。让我知道如果您遇到任何障碍。

I believe that's correct. Let me know if you run into any snags.

当您添加眼睛的颜色或任何其他特征,你可能必须做一些与preference不同。我有4列在这一点上:的id,USER_ID,foreign_id,foreign_type

When you add eye color or any other characteristic, you'll probably have to do something different with preference. I'd have 4 columns at that point: id, user_id, foreign_id, foreign_type

foreign_id会从eye_color / hair_color表中的ID,并foreign_type将是眼睛或毛什么的。然后,在你的模型,你有这样的事情:

foreign_id would be the id from the eye_color/hair_color table, and foreign_type would be "eye" or "hair" or something. Then in your model, you'd have something like this:

#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。

That gets a little crazy, but it's the most DRY way of doing it. You'd put the same thing in your eye_color.rb and just replace "hair" with "eye" for the foreign_type.

这篇关于扶手:我如何模型$ P ​​$ pferences?我应该使用的has_many:通过?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆