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

发布于 2024-11-27 23:44:11 字数 589 浏览 4 评论 0原文

我有一个模型如下:

 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 表中为 Icon 表中的外键设置两个字段,但标记不同。

我将一个外键属性称为 icon_id,将另一个外键属性称为 user_icon_id。

要做到这一点,以下是正确的:

Greeting

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

I have a model as follows:

 Greeting

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

I need to save the icon_id and also the user_icon id in the case I don't have a registered user.

Is this correct? Will I be able to access the icon by doing the following:

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

I want to improve this question so let me explain it better:

I want to save two objects from the same model in another model.

So Greeting belongs to Icon but I will have two fields in the Greetings table for foreign keys from the Icons table but labeled differently.

I call one foreign key attribute icon_id and the other user_icon_id.

To do this is the following correct:

Greeting

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

方圜几里 2024-12-04 23:44:11

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

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

如果您以Rails无法将其转换为模型名称的方式更改has_one,has_many或belongs_to关联中的字段名称,您需要告诉 Rails 你真正指的是哪个模型,因此是 :class_name

Almost correct, you need something like this:

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

If you change the name of the field in a has_one, has_many or belongs_to association in such a way that Rails can't convert it into a model name, you need to tell Rails which model you actually mean, hence the :class_name.

小忆控 2024-12-04 23:44:11

没有。 需要。

belongs_to :user_icon, :foreign_key => :user_icon

如果您希望有一个使用数据库中的外键用户图标的greeting.user_icon 访问器,则

Nope. You need

belongs_to :user_icon, :foreign_key => :user_icon

If you want to have a greeting.user_icon accessor using the foreign key user icon in your database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文