Hi, I have a table like this in schema.rb create_table "ac_rooms", :force => true do |t| t.column "roomname", :string, :limit => 50, :default => "", :null => false t.column "updated", :float, :default => 0.0, :null => false t.column "lines", :integer, :limit => 8, :default => 0, :null => false t.column "created_at", :datetime end and another in migration like this def self.up create_table :line_msgs do |t| t.column :sender_nick, :string t.column :content, :string t.column :room_id, :integer, :null => false t.column :send_at, :timestamp end execute "alter table line_msgs add constraint fk_line_msg_rooms foreign key (room_id) references ac_rooms(id)" end and i added the belongs_to :ac_room in line_msg.rb and has_many: :line_msgs to ac_room.rb in the model, but when i did room = AcRoom.find(...) <%= render(:partial => "line_msg", :collection => room.line_msgs) %> but i get error Mysql::Error: #42S22Unknown column ''line_msgs.ac_room_id'' in ''where clause'': SELECT * FROM line_msgs WHERE (line_msgs.ac_room_id = 6) my question is why rails make it into line_msgs.ac_room_id but not line_msgs.room_id, is there some stupid things i did, thanks. Excuse me for my poor english -- Posted via http://www.ruby-forum.com/.
Mark Reginald James
2006-Jul-15 14:00 UTC
[Rails] Re: model navigation problem with foreign key
Jia Liu wrote:> def self.up > create_table :line_msgs do |t| > t.column :sender_nick, :string > t.column :content, :string > t.column :room_id, :integer, :null => false > t.column :send_at, :timestamp > end > > execute "alter table line_msgs > add constraint fk_line_msg_rooms > foreign key (room_id) references ac_rooms(id)" > end > > and i added the belongs_to :ac_room in line_msg.rb and has_many: > :line_msgs to ac_room.rb in the model, but when i did > > room = AcRoom.find(...) > <%= render(:partial => "line_msg", :collection => room.line_msgs) %> > > but i get error > > Mysql::Error: #42S22Unknown column ''line_msgs.ac_room_id'' in ''where > clause'': SELECT * FROM line_msgs WHERE (line_msgs.ac_room_id = 6) > > my question is why rails make it into line_msgs.ac_room_id but not > line_msgs.room_id, is there some stupid things i did, thanks. > Excuse me for my poor englishIf you want Rails to use room_id as the foreign key, rather than the default ac_room_id, you have to write the belongs_to as: belongs_to :ac_room, :foreign_key => ''room_id'' -- We develop, watch us RoR, in numbers too big to ignore.