Reputation: 12079
I'm trying to bind a param to a join via a named scope., but I'm getting an error.
What is the correct way to do that?
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.with_vote(request.ip).all
I believe I need the condition definition in the model for it to appear in the ON clause of a JOIN, rather then in the WHERE one.
Edit I'm trying to get the following query
select Ideas.*, Votes.* from Ideas
left outer join Votes
on Votes.Idea_id = Idea.id AND Votes.ip = {request.ip}
Upvotes: 0
Views: 161
Reputation: 8894
I do not think you can use incomplete conditions in an association. If I understand correctly, you need Idea has many votes and votes records the request.ip and idea id. You want the scope to retrieve all ideas your current request ip voted for.
class Idea
has_many :votes
scope :with_vote_from_ip, lambda {|ip| {
:include => [:votes],
:conditions => ['votes.ip = ?', ip]
}}
end
but if you want all ideas including only votes from current up you need extra conditions on the outer join. I think this is not possible without sql fragment:
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
now Idea.with_vote_from_ip(request.ip).all
should work.
Upvotes: 1