Search code examples
ruby-on-rails-3.2model-associations

How to connect this model association both belongs_to_through and belongs_to?


Here are my models:

**Resource**
has_many :users, :through => :kits
has_many :kits

**User**
has_many :resources, :through => :kits
has_many :kits

**Kits**
belongs_to :resource
belongs_to :user

Users in the application can add resources to their kits by clicking on them. Then I can find out which resource a User has by doing:

@user.resources

Now a user can also submit a resource for approval. I want to track which user submitted which resource. How can I do this so that I can do the following:

Resource Controller

def create
current_user.resources.create(params[:resource])
end

I would like to be able to do something like:

@user.submitted_resources.count

Solution

  • Given models with the following associations (and the necessary tables, columns, etc.):

    **Resource**
    has_many :users, :through => :kits
    has_many :kits
    belongs_to :submitter, class_name: "User"
    
    **User**
    has_many :resources, :through => :kits
    has_many :kits
    has_many :submitted_resources, class_name: "Resource", foreign_key: "submitter_id"
    
    **Kits**
    belongs_to :resource
    belongs_to :user
    

    Note the added has_many :submitted_resources, class_name: "Resource", foreign_key: "submitter_id" on the User model. This assumes that there is a column on the Resources table named submitter_id (which you said you had added). After adding this association, you can reference all the resources a User has submitted with the User#submitted_resources method (i.e. @user.submitted_resources.count).

    I also added the belongs_to :submitter, class_name: "User" association to your Resource model, which allows for easy referencing the User that created the record, but it isn't necessary to accomplish what you asked.