I’m setting up an app for posting items wanted/available/bartering. I’ve got two main classes, Post and Item.
Each post contains an offered_item, a wanted_item, or both. Here are my current definitions:
class Post < ActiveRecord::Base
has_one :wanted_item, :class_name => 'Item', :dependent => :destroy
has_one :offered_item, :class_name => 'Item', :dependent => :destroy
has_one :location, :dependent => :destroy
end
and
class Item < ActiveRecord::Base
belongs_to :post
attr_accessible :title, :description
end
On to my question: How do I structure the foreign keys in the Items table such that I can tell which post (and whether it’s a wanted_item or offered_item)? Is this done in the migrations files or in the models?
As it currently sits, when I try a query like:
Post.find(:first).wanted_item
I get the following:
SQLite3::SQLException: no such column: items.post_id: SELECT
“items”.* FROM “items” WHERE “items”.”post_id” = 1 LIMIT 1
You can set conditions on associations, like so:
and add a
kindcolumn toItem(don’t use “type”, it’s a reserved word).EDIT: reading your post again, your
Itemtable seems to be lacking the foreign key. In your migration file that creates yourItemtable, simply includet.references :postto have rails create a post_id foreign key column.