我想使用ActiveRecord来处理我的表数据,但是如果我的表名是可变的,那该怎么办呢。此代码将生成错误。有什么建议吗?
name = "Posts"
class name < ActiveRecord::Base
end
答案 0 :(得分:1)
我相信你可以做以下事情:
name = 'Post' # Dynamically generate the class name
klass = Class.new(ActiveRecord::Base) do
# This is the base class.
# You can pass a block with new
# methods here if you'd like.
end
Object.const_set name, klass
name.constantize.new # Call your class dynamically :)
答案 1 :(得分:0)
您可以执行以下操作,从变量中设置table_name:
class Post < ActiveRecord::Base
def self.table_name
# Some method to determine and set the table name.
# Must return a string with a table name. E.g. the
# following would set the table name to `posts_2015-11-15`
"posts_#{Date.today}"
end
# ...
end