模型有两个属于另一个模型的属性
我有一个模型如下:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
几乎是正确的,您需要这样的东西:
如果您以Rails无法将其转换为模型名称的方式更改
has_one,has_many或belongs_to
关联中的字段名称,您需要告诉 Rails 你真正指的是哪个模型,因此是:class_name
。Almost correct, you need something like this:
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
.没有。 需要。
如果您希望有一个使用数据库中的外键用户图标的greeting.user_icon 访问器,则
Nope. You need
If you want to have a greeting.user_icon accessor using the foreign key user icon in your database.