MxLDevs
MxLDevs

Reputation: 19506

What is the appropriate association for joining two unrelated models

I have two models, FlyerItem and Product. If you think of a flyer for an electronics store it might show a TV on sale. For this particular case, I suppose that a flyer item advertises one product.

I've defined the model for the flyer item like this

class FlyerItem < ActiveRecord::Base
  has_one :product
end

The migration looks like this

class CreateFlyerItems < ActiveRecord::Migration
  def change
    create_table :flyer_items, :primary_key => :flyer_item_id do |t|
      t.references :product
    end
  end
end

Then in my View I try to access a particular instance of an item like this

<% FlyerItem.find do |item| %>
  <p><%= item.product %></p>
<% end %>

However rails throws an exception

PG::UndefinedColumn: ERROR:  column products.flyer_item_id does not exist
LINE 1: SELECT  "products".* FROM "products"  WHERE "products"."flye...
                                                    ^
: SELECT  "products".* FROM "products"  WHERE "products"."flyer_item_id" = $1  ORDER BY "products"."product_id" ASC LIMIT 

Which is expected, because a product really has nothing to do with a flyer item, so the Product table doesn't and shouldn't have that column.

What I really want to say is something like

SELECT * FROM flyer_items WHERE flyer_items.product_id = products.product_id

What kind of association would I use here?
Is an association even the correct approach?

A flyer must have one product, but a product does not necessarily need to be assigned to any flyers.

Upvotes: 1

Views: 241

Answers (1)

Chris Cherry
Chris Cherry

Reputation: 28554

Instead of has_one you want belongs_to. The belongs_to association method goes on the class that has the foreign key column. On the opposite side of the association you can use has_many or has_one depending on your needs.

class FlyerItem < ActiveRecord::Base
  belongs_to :product
end

class Product < ActiveRecord::Base
  has_many :flyer_items
end

Upvotes: 1

Related Questions