Rails find won't attach when args are added

I hope I am doing something wrong and someone can point me in the right direction ...

I wrote a method inside one of my models, here is the code:

def self.find_by_user_id(user_id, *args)
    self.find(:all, :joins => :case_map,
       :conditions => ['case_maps.uer_id = ? and case_maps.case_id = cases.id', user_id], 
        *args)
end

      

I can call code like this and it works as expected:

Case.find_by_user_id(some_user_id)

      

However, when this code is executed with any additional arguments, for example:

Case.find_by_user_id(some_user_id, :limit => 15)

      

I return ALL cases. The request in my log file shows it did this:

Case Load (0.6ms)   SELECT * FROM `cases` LIMIT 15

      

I even put a logger.info message in this method to make sure it is the one that is being executed ... It seems that whenever args is non-zero, it skips all the conditions and connections that I added to find and just uses * args.

Does anyone see something I am doing wrong?

+2


source to share


1 answer


AR :: B # find expects a variable number of arguments, but the last one must be hash parameters. It uses Array#extract_options!

and you can also:

def self.find_by_user_id(user_id, *args)
  options = args.extract_options!
  options.merge!(:joins => :case_map, :conditions => 
    ['case_maps.uer_id = ? and case_maps.case_id = cases.id', user_id])
  self.find(:all, *args, options)
end

      

But you shouldn't. What possible values ​​make sense between the fields: all and options?

What are you really after:

def self.find_by_user_id(user_id, options)
  self.find(:all, options.merge(:joins => :case_map, :conditions => 
    ['case_maps.user_id = ? and case_maps.case_id = cases.id', user_id]))
end

      

Or better:



named_scope :find_by_user_id, lambda{|user_id|
  {
    :joins => :case_map,
    :conditions => ['case_maps.user_id = ? and case_maps.case_id = cases.id', user_id]
  }
}

      

The named scope ensures that all your parameters are fully merged (all your conditions will be applied, even if you add later). Then you can call it with:

Case.find_by_user_id(user_id).all(:limit => 15)

      

(The Scope's name is "Da Bom", everyone should use them as much as possible. Even in general conversation. For example, if you were here at my house last night, you might have heard this little melody: "What do you want to eat?" , "The same thing I have every night, Named Areas and Chips. Because I'm perfect and all of that.)

Also, as a side note, if this applies to your Case model, the " and case_maps.case_id = cases.id

" clause is unnecessary, :joins => :case_map

does it for you.

+3


source







All Articles