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,

class User
  has_many :tasks, dependent: :destroy, foreign_key: :user_id
end
class Task
  belongs_to :user
end

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.

has_one :user, foreign_key: :creator_id, class_name: "User"

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”:

has_one :creator, foreign_key: 'creator_id', class_name: "User"

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

class Task
  belongs_to :user
  belongs_to :creator, foreign_key: 'creator_id', class_name: 'User'
end

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:

@task.user    # the User who is assigned the task
@task.creator # the User who created the task
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement