Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call app Model in initializers with Ruby on Rails

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.

like image 892
Abid Hussain Avatar asked Mar 27 '14 06:03

Abid Hussain


People also ask

How do Initializers work in Rails?

An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.

What is application RB in rails?

The configuration file config/application. rb and environment-specific configuration files (such as config/environments/production. rb ) allow you to specify the various settings that you want to pass down to all of the components. For example, you could add this setting to config/application.rb file: config.

What is model in Ruby on Rails?

6.1 Generating a Model A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record.


2 Answers

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
like image 110
rainkinz Avatar answered Sep 30 '22 20:09

rainkinz


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
like image 40
danielsmith1789 Avatar answered Sep 30 '22 20:09

danielsmith1789