Raul
Raul

Reputation: 299

How to access multiple models in a single contoller, Ruby on Rails?

Here is my index method, which is trying to access 2 different Models i.e., Session & Email:

def index
    user_session = Session.find_by_user_id(user_id)

if !user_session.blank?
  if setting_orig = GlobalSetting.find_by_settings_session_id(user_session.id)
      @setting = setting_orig.dup
  end

else
  @setting = GlobalSetting.first.dup
end 

end

But, when I try to create this form:

<%= form_for(@setting) do |f| %>
 <%= f.text_field :username %>
 <%= f.password_field :password %>
<%= f.submit "Submit" %>

i am shown this error, undefined method 'model_name' for NilClass:Class. How to make it work, any suggestion ?

Upvotes: 0

Views: 125

Answers (1)

Joey Hoang
Joey Hoang

Reputation: 406

Unixmonkey has the right idea, look at your stack trace and figure out where the error is coming from.

Also, you have a hole in your statement logic. If the user_session isn't blank (SOMEONE is logged in) but you can't find an email with setting_session_id equal to user_session.id (user doesn't have an email perhaps?) then @setting never gets declared, thus you will run into your error.

def index
  user_session = Session.find_by_user_id(user_id)

  if !user_session.blank? AND setting_orig = GlobalSetting.find_by_settings_session_id(user_session.id)
    @setting = setting_orig.dup
  else
    @setting = GlobalSetting.first.dup
  end 
end

Upvotes: 2

Related Questions