Rails - problem with HABTM
I have two models:
ItemType and PropertyType, they are connect with HAB开发者_运维知识库TM 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"
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])
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
精彩评论