views:

37

answers:

2

Hello everyone.

I have two models:

ItemType and PropertyType, they are connect with HABTM relation.

But this code doesn't work:

PropertyType.find(:all, :conditions => ["item_type_id != ?", existing_type_id])

I have error:

Mysql::Error: Unknown column 'item_type_id' in 'where clause': SELECT * FROM `property_types` WHERE (item_type_id != '3')

How to solve this? I want to find all PropertyTypes where item_type_id != "some_id"

A: 

It looks like you're missing that column on your property_types table. Did you write/run your migration scripts after creating the models? Models do not know anything or control anything in the database, including its schema.

ruby script/generate model will automatically create a basic migration for you, but you'll probably need to flesh it out and run it with rake db:migrate

Zachary
no. this is HABTM, so i have JOIN-table.
rbdev
try: PropertyType.find(:all, :include => :item_types, :conditions => ["property_types_item_types.item_type_id != ?", exsiting_type_id])
Zachary
@Zachary I believe that's almost right but the join table would be named in alphabetical order. I.e. `item_types_property_types`
bjg
Ahh, sorry about that, wasn't sure off the top of my head how Rails ordered it.
Zachary
+1  A: 

I have assumed the following from your description.

class ItemType
  has_and_belongs_to_many :property_types
end

class PropertyType
  has_and_belongs_to_many :item_types
end

create_table :item_types_property_types, :id => false do |t|
  t.references :item_type, :property_type
end

then your query would look like this:

PropertyType.find(:all, :include => :item_types, :conditions => ["item_types_property_types.item_type_id != ?", existing_type_id])
bjg