umerh
umerh

Reputation: 160

Rails Associations: One way associations

I am learning Rails and ActiveRecord stuff but I am kind of stuck on this small problem.

Lets say you I a product (Stock) and every product has a colour, normally the right way is to setup an association. Please take a look at the below code:

class Stock < ActiveRecord::Base
 attr_accessible :size, :colour_id
end

class Colours < ActiveRecord::Base
 belongs_to :stock
end

Actually what I want to be able to do is

p @stock_item.colour.name
# But I get this error
SQLite3::SQLException: no such column: colours.stock_id: SELECT  "colours".* FROM "colours"  WHERE "colours"."stock_id" = 1 LIMIT 1

When in fact the query should have been:

SELECT  "colours".* FROM "colours"  WHERE "colours"."id" = "stock"."colour_id"

As colours are all unique in reality a property of the Stock item. How can I setup an association this way so that I could do:

p @stock_item.colour.name
> Red

Thanks.

Umer

Upvotes: 1

Views: 1836

Answers (1)

jvnill
jvnill

Reputation: 29599

you need to add a belongs_to association to stock and not to colour since stock has the colour_id

class Stock < ActiveRecord::Base
  belongs_to :colour
end

and you most probably want a has_many association on colour

class Colour < ActiveRecord::Base
  has_many :stocks
end

Upvotes: 6

Related Questions