model有两个属于另一个模型的属性

时间:2011-08-05 10:35:55

标签: ruby-on-rails-3 model model-associations

我的模型如下:

 Greeting

  belongs_to :icon
  belongs_to :icon, :foreign_key => :user_icon

如果我没有注册用户,我需要保存icon_id和user_icon id。

这是对的吗?我是否可以通过执行以下操作来访问该图标:

@greeting.icon.name
@greeting.user_icon.name

我想改进这个问题,让我更好地解释一下:

我想在另一个模型中保存同一模型中的两个对象。

所以Greeting属于Icon,但我会在Greetings表中有两个字段,用于来自Icons表的外键,但标记方式不同。

我调用一个外键属性icon_id和另一个user_icon_id。

为此,请执行以下操作:

Greeting

belongs_to :icon
belongs_to :icon, foreign_key => :user_icon_id

2 个答案:

答案 0 :(得分:1)

几乎正确,你需要这样的东西:

belongs_to :icon
belongs_to :user_icon, :class_name => "Icon", foreign_key => :user_icon_id

如果更改has_one, has_many or belongs_to关联中字段的名称,使Rails无法将其转换为模型名称,则需要告诉Rails您实际意味着哪个模型,因此{{ 1}}。

答案 1 :(得分:0)

不。你需要

belongs_to :user_icon, :foreign_key => :user_icon

如果您想使用数据库中的外键用户图标来拥有greeting.user_icon访问者。

相关问题