开发者

set_table_name only works once?

开发者 https://www.devze.com 2023-03-31 16:37 出处:网络
I\'m trying to use set_table_name to use one generic model on a couple different tables.However, it seems as though set_table name only works on the class once per application session.For instance in

I'm trying to use set_table_name to use one generic model on a couple different tables. However, it seems as though set_table name only works on the class once per application session. For instance in a rails 3 console (ruby 1.8.7) the following happens:

GenericModel.set_table_name "table_a"
puts GenericModel.table_name # prints table_a
pp GenericModel.column_names # prints the columns associated with table_a

GenericModel.set_table_name "table_b"
puts GenericModel.table_name # prints table_b
pp GenericModel.column_names # still prints the columns associated with table_a

Currently the workaround I've found is to also add .from(table_b) so that queries don't error out with 'table_b.id doesn't exist!' because the query still thinks it's FROM table_a.

Can others reproduce the issue? Is this the intended behaviour of set_table_name?

UPDATE

Adding

Model.re开发者_开发百科set_column_information

after set_table_name forces the model to work as I expect. Reference found in http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000368


This is probably an undocumented limitation. Once the SHOW FIELDS FROM has been executed, which is where the results from column_names comes from, it is usually cached, at least for the duration of the request. If you must, try using the console reload! method to reset things.


your choice

rename_table

more info at AR TableDefinition

0

精彩评论

暂无评论...
验证码 换一张
取 消