How to call app Model in initializers with Ruby on Rails

狂风中的少年 提交于 2020-01-04 09:14:00

问题


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:

  1. First I check if the table exists.
  2. Then I check if my record exists.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!