1

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.reset_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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think you're on the right track. The reason this has come up is because my app runs properly in development mode. However, when running tests or deploying on production errors occur due to the incorrect table name in the sql from. This makes sense because production is probably caching a lot more than development.
The answer to this problem is: Model.reset_column_information
Marking you as the answer since you pointed me in the right direction by identifying the root cause.
0

your choice

rename_table

more info at AR TableDefinition

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.