开发者

Advanced find in Rails

I really suck at Rails' finders besides the most obvious. I always resort to SQL when things get more advanced than

Model.find(:all, :conditions => ['field>? and field<? and id in (select id from table)', 1,2])

I have this method:

def self.get_first_validation_answer(id)
a=find_by_sql("
  select answers.*, answers_registrations.answer_text
  from answers_registrations left join answers on answers_registrations.answer_id=answers.id
  where 
    (answers_regi开发者_JAVA技巧strations.question_id in (select id from questions where validation_question=true)) 
    and
    (sale_registration_id=#{id})
  limit 1
").first

a.answer_text || a.text if a
end

Can someone create a find method that gets me what I want?

Regards,

Jacob


class AnswersRegistration < ActiveRecord::Base
  has_many :answers
end

id = 123
the_reg = AnswersRegistration.first(
  :joins => :answers, 
  :conditions => '(question_id in (select id from questions where validation_question = true)) and (sale_registration_id = ?)', id)

(untested)


Just use binarylogic's Searchlogic gem if that satisfies your need. Here you go: http://github.com/binarylogic/searchlogic


Sometimes AR will choke on complicated nested conditions, but in theory you should be able to do this:

AnswersRegistration.first(:conditions => { :question => { :validation_question => true },
                                           :sale_registration_id => id },
                          :include => :answer) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜