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 abl开发者_如何学Pythone 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
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
.
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.
精彩评论