Ruby on rails 3 rails将返回nil的include查询转换为作用域lambda
以下查询在某些情况下返回nilRuby on rails 3 rails将返回nil的include查询转换为作用域lambda,ruby-on-rails-3,Ruby On Rails 3,以下查询在某些情况下返回nil scope :claim_one, where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL " ).includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL') 我想将查询转换成一个lambda函数,该函数处理查询返回的nil,如下所示 scope :claim, (lamb
scope :claim_one, where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL " ).includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL')
我想将查询转换成一个lambda函数,该函数处理查询返回的nil,如下所示
scope :claim, (lambda do |claim| where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL ").includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL', claim ) unless claim.nil? end )
后者不起作用,因为我认为它没有正确的rails语法
谢谢我不确定自己是否完全理解(见上面的评论),但我希望这会有所帮助。我认为代码的结果将是一个ActiveRecord::Relation,其中没有记录,而不是零。我假设“claim”是您希望传入的参数。如果是这种情况,您可以按如下方式添加它 现在处理lambda示波器的首选方法要好得多;只需使用类方法:
def self.claim_one(claim)
return [whatever you want] unless claim
where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL " ).
includes(:instructor_assignments).
where('instructor_assignments.user_id IS NULL')
end
不过,我建议您采取以下措施,使您的作用域更易于单独使用、更易于理解和测试,并且更方便使用:
def self.incomlete()
where(" location_id IS NULL OR start_time IS NULL OR archived IS NULL " )
end
def self.without_instructor()
includes(:instructor_assignments).where('instructor_assignments.user_id IS NULL')
end
要将其命名为,我将使用以下内容:
result = YourModel.incomplete.without_instructor
if result.empty?
# do yo funky "ain't got no records dance"
else
# record jackpot!
end
这回答了你的问题吗?很好,我应该用一种更好的方式陈述事情 我用的是来自加拿大的坎坎宝石 在我看来,我有以下代码:
<% if can? :claim, @workshop %>
<%= link_to claim_workshop_path(@workshop), :method => :post , :class => "mybtn btn-mini claim-workshop-button" do %>
<%= t(:Claim) %>
<%= content_tag(:i, "", :class => "icon-thumbs-up").html_safe %>
<% end %>
<% end %>
在类User中,我定义了需要它来获得结果的范围
scope :claim, where(" location_id IS NOT NULL OR start_time IS NOT NULL " ).includes(:instructor_assignments).where('instructor_assignments.user_id IS NOT NULL')
你好。对不起,你说的“照顾零”是什么意思?要避免ActiveRecord::RecordNotFound错误,还是在查询未返回结果时返回其他值?还有一件事:“claim”是要传递给查询的参数,还是要将其绑定到查询结果?您可能还需要遵循
def self.claim\u One(claim)中的范围定义
带有参考(:讲师作业)
--另请参见
scope :claim, where(" location_id IS NOT NULL OR start_time IS NOT NULL " ).includes(:instructor_assignments).where('instructor_assignments.user_id IS NOT NULL')