Search code examples
ruby-on-railsrubymodelpolymorphic-associations

Associating a User to model via id


I'm having some difficulty expressing a linkage of a User to my Listing model.

I set up a Rails form when I associated a designer_id (added to listing_params as a private controller method) that would link a selected user to a Listing model when created:

#migration
add_column :listings, :designer_id, :integer

_form.html.erb
<%= collection_select :listing, :designer_id, @account.users, :id, :name, prompt: "Choose..." %>

Checking in the console, the form returned the correct user id as designer_id. Success!

What I need to do now is access the User name using a Listing method, but I'm getting stuck- the issue is primarily making the translation from the id procured to the User referenced:

 #listing.rb

  def designer
    self.designer_id == User.find_by_id(params[:name])
    if self.designer_id = nil
      return "N/A"
    else   
      return "#{User.name}"
  end

Much appreciated!


Solution

  • in the migration if you are on at least rails 4 you can do

    add_reference(:listings, :designer) you may need to do add_reference(:listings, :designer, :foreign_key => { to_table: 'users'}

    other options I often use add_reference(:listings, :designer, :foreign_key => { to_table: 'users'} index: true, limit: 8)

    Migration aside you can do this in the models.

    class Listing
      belongs_to :designer, class_name: 'User', inverse_of: :listings
    
    
    end
    

    and in users

    class User
      has_many :listings, inverse_of: :designer, dependent: :destroy
    end
    

    Getting the users name would then be,

    listing.designer.name

    if you are doing this in a controller you will want to pre-load the association so you are not introducing an n+1 query to a list of listings.