Search code examples
ruby-on-railsactiverecordnomethoderror

NoMethodError in rails using multiple conditions


I can't seem to get the logic for my conditions to work for this query. I can get @showemail = PreferenceSetting.find(1) to work...but when I try to add conditions, it keeps throwing a "NoMethodError". I am fairly new at rails and am really stuck on this.

 def show
   @showemail = PreferenceSetting.where('user_id = ?', params[:u]).where('user_preference_id = ?', 1)
 end

This is my code for the view

 <%= @showemail.prefers %>

Every time I try to access the 'show' view it says "undefined method `prefers'.

My Models

class PreferenceSetting < ActiveRecord::Base
  belongs_to :users_preference,  inverse_of: :preference_settings
  belongs_to :user, inverse_of: :preference_settings
end

class UserPreference < ActiveRecord::Base has_many :preference_settings, inverse_of: :user_preference end


Solution

  • find returns an instance whereas your where methods return an ActiveRecord::Relation object.

    Adjust the code of your show action like this:

    def show
      conditions = {user_id: params[:u], user_preference_id: 1}
      @showemail = PreferenceSetting.where(conditions).last
    
      # you could also use: PreferenceSetting.find_by(conditions)
    end