开发者

How to share a variable between a model and a controller ? (Rails3)

开发者 https://www.devze.com 2023-04-01 10:55 出处:网络
How to share a variable between a model and a controller with Rails 3.1 开发者_Python百科? It\'s for changing which table the Model has to hit.

How to share a variable between a model and a controller with Rails 3.1 开发者_Python百科?

It's for changing which table the Model has to hit.

Any idea to do that in a Rails Way ?

Thanks a lot


E.g. This shares table_to_hit:

class MyController < ApplicationController
  def my_action
    table_to_hit = params[:table_to_hit]
    @foo = MyModel.my_class_method(table_to_hit)
  end
end

class MyModel < ActiveRecord::Base
  def self.my_class_method(table_to_hit)
    # do something
  end
end


Article.set_table_name(TABLE_NAME)


it's bad idea.

Better sulution example. You use 2 tables: table_1, table_2.

make AbstractTable model

class AbstractTable << AR::Base
  self.abstract_class = true

  @@tables_models = {}      

  def self.inherited(klass)
   raise 'Duplicate table error' if @@tables_models[klass.table_name]
   @@tables_models[klass.table_name] = klass
  end

  def self.get_model_for_table(table_name)
   table_name = table_name.to_s
   @@tables_models[table_name]
  end
  ...
  def foo

  end
end

class Table1 << AbstractTable
    self.table_name = '23424'

    def bb
    end
end

class Table2 << AbstractTable
    self.table_name = 'table_werw23424'       
end


AbstractTable.get_model_for_table('23424')
0

精彩评论

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