问题
I am new in Ruby on Rails and i am using Ruby version 2.1.0 and Rails 4.0.2
My Query is:-
I want to call Model in initializers.
my Model file is setting.rb and Model name Setting. its location is app/model directory.
I want to call Setting Model in initializers file paypal.rb.
paypal.rb location is config/initializers/paypal.rb.
Please help how to call Model in initializers in Ruby on Rails.
回答1:
Do you want to make sure all other initializers have run before running this one? If so you could do this:
# config/initializers/paypal.rb
Rails.configuration.after_initialize do
paypal_settings = Setting.find_by(name: "paypal")
# do something with paypal settings...
end
回答2:
To get around that problem I did this:
- First I check if the table exists.
- Then I check if my record exists.
- Otherwise I just set a default value.
It's kind of a hack but it works for my use case.
if ActiveRecord::Base.connection.table_exists? :settings # check if table exists
if Setting.first.present? # check if first record has been seeded
NUMBERS = Setting.first.my_numbers.split(",")
else
NUMBERS = '987654321'
end
else
NUMBERS = '123456789'
end
回答3:
In the rails, wherever you are, you can interact with Models. Like
Setting.method_name()
Inside the rails application, you can create your own new folder(expect default directories created by rails new command) and can interact with Model methods.
来源:https://stackoverflow.com/questions/22680047/how-to-call-app-model-in-initializers-with-ruby-on-rails