Skip to content
Advertisement

How can I introduce a has_one_belongs_to_one association in Rails model?

My Rails application has users and tasks created by users. Users can also create a task and assign another user to it. I am not quite sure how to build associations here.

I know since a task is created by a user, I can have an association as below,

I also want to add an association for creator in the Task model but I am not sure how to do it since a creator will also be an instance of the User class and I already have a belongs_to association with User

I tried to add an association for creator in Task model in the following way but it didn’t work.

Advertisement

Answer

Since you’ve already defined the belongs_to :user method, the method @task.user is already taken by that association. You can’t use the same name for a different method, so you’ll have to use a different name for that association.

The association name doesn’t have to be the same as the model. You can name the creator association something else, like “creator”:

Since the task has a foreign key for the creator, you should be able to use belongs_to for both associations:

Here’s a discussion about the difference between has_one and belongs_to: What’s the difference between belongs_to and has_one?

Either way way you can do:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement