Ruby on rails 将参数从控制器传递到模型条件

Ruby on rails 将参数从控制器传递到模型条件,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我试图通过命名作用域将参数绑定到联接,但出现错误 正确的方法是什么 class Idea < ActiveRecord::Base #relations has_many :votes, :inverse_of => :idea has_one :has_voted, :class_name => 'Vote', :conditions => ['ip = :ip'] # named scopes scope :with_vot

我试图通过命名作用域将参数绑定到联接,但出现错误

正确的方法是什么

class Idea < ActiveRecord::Base

    #relations
    has_many :votes, :inverse_of => :idea
    has_one :has_voted, :class_name => 'Vote', :conditions => ['ip = :ip']

    # named scopes
    scope :with_vote, lambda {|ip| {
        :include => [:has_voted],
        # like this ??
        :conditions => [:has_voted => {:conditions => {:userIp => ip}} ] 
    }}

end

我认为你不能在协会中使用不完整的条件。 如果我理解正确,您需要Idea有许多投票,投票记录request.ip和Idea id。 您希望范围检索您当前请求ip投票支持的所有想法

class Idea
  has_many :votes

  scope :with_vote_from_ip, lambda {|ip| {
    :include => [:votes],
    :conditions => ['votes.ip = ?', ip] 
  }}
end
但是如果你想要所有的想法,包括当前的投票,你需要额外的条件在外部连接。我认为如果没有sql片段,这是不可能的:

class Idea
  has_many :votes

  scope :with_vote_from_ip, lambda {|ip| {
    :joins => 'left outer join Votes on Votes.Idea_id = Idea.id AND Votes.ip = #{ip}' 
  }}
end

现在
Idea。使用来自\u ip(request.ip)的\u vote\u。所有的
都应该工作。

我想要所有的想法和一个标志,指示当前用户是否投票支持它。在这种情况下,我得到以下查询:
SELECT。。。从“ideas”左外连接到“ideas”上的“ideas”投票。“ideas”id“=”ideas“,“id”WHERE(voates.ip='127.0.0.1”)
并且ip显示在WHERE上,而不是ON子句上。这正是我实现它的方式,尽管不能用ActiveRecord的方式实现。谢谢;)
class Idea
  has_many :votes

  scope :with_vote_from_ip, lambda {|ip| {
    :joins => 'left outer join Votes on Votes.Idea_id = Idea.id AND Votes.ip = #{ip}' 
  }}
end