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}
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.
Related
I have (in Rails 3.2.13):
class User < ActiveRecord::Base
has_many :app_event_login_logouts
end
class AppEventLoginLogout < ActiveRecord::Base
belongs_to :user
end
and would like to get back something like:
AppEventLoginLogoug.select("id, type, users.email").joins(:user)
basically id, type from app_event_login_logouts and email from users but this doesn't seem to be working. What would be the correct syntax?
Try out following code:
ret = User.joins(:app_event_login_logouts).select('app_event_login_logouts.id, app_event_login_logouts.type, users.email')
ret.first.id # will return app_event_login_logouts.id
ret.first.email # will return users.email
...
AppEventLoginLogoug.find(:all,
{:include => [:users],
:select => ['id', 'type', 'users.email']})
I also checked the apidoc and found something like that:
result= AppEventLoginLogoug.find(:all,
:conditions => ['condition_here'],
:joins => [:users],
:select => 'whatever_to_select'
:order => 'your.order')
I have some model classes like this:
class Organisation < ActiveRecord::Base
has_many :dongles
has_many :licences_on_owned_dongles, :through => :dongles, :source => :licences,
:include => [:organisation, :user, :owner_organisation, :profile, :dongle,
{:nested_licences => [:profile]} ]
end
class Dongle < ActiveRecord::Base
has_many :licences
belongs_to :organisation
end
class Licence < ActiveRecord::Base
belongs_to :dongle
# tree-like structure. I don't remember why this had to be done but the comment says
# "find a way to make the simpler way work again" and I tried using the simpler way
# but tests still fail. So obviously the SQL awfulness is necessary...
default_scope :conditions => { :parent_licence_id, nil }
has_many :nested_licences, :class_name => 'Licence', :dependent => :destroy,
:autosave => true,
:foreign_key => :parent_licence_id,
:finder_sql => proc {
"SELECT l.* FROM licences l WHERE l.parent_licence_id = #{id}" },
:counter_sql => proc {
"SELECT COUNT(*) FROM licences l WHERE l.parent_licence_id = #{id}" }
end
Now I can do this:
test "getting licences on owned dongles" do
org = organisations(:some_other_corp)
assert_equal [licences(:licence_4)], org.licences_on_owned_dongles
end
That happily passes. Since it's an association, you might thing you can find() on it:
test "getting licences on owned dongles and then filtering further" do
org = organisations(:some_other_corp)
conditions = { :owner_organisation_id => nil }
assert_equal [licences(:licence_4)],
org.licences_on_owned_dongles.find(:all, :conditions => conditions)
end
But this gives:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: dongles.organisation_id: SELECT "licences".* FROM "licences" WHERE "licences"."parent_licence_id" IS NULL AND (("dongles".organisation_id = 72179513)) AND ("licences".parent_licence_id = 747059259)
test/unit/organisation_test.rb:123:in `test_getting_licences_on_owned_dongles_and_then_filtering_further'
In fact, this even occurs when all you call is find(:all). It isn't just SQLite either, because I noticed this in production (oops) on MySQL.
So I don't know. It's really too mysterious to investigate further. I might shelve it as a "Rails just can't do find() on an association", use a block to filter it and leave it at that. But I wanted to put it out, just in case there is a better option.
(Actually if you look at the query Rails is generating, it is complete nonsense. Somehow it has ended up generating a query where something has to be NULL and equal to a value at the same time. Even if the query worked, this will return 0 rows.)
Don't use find in a Rails 3 app.
org.licences_on_owned_dongles.find(:all, :conditions => conditions)
should be
org.licences_on_owned_dongles.where(conditions)
Edit: Read up on it here.
I think you're looking for .where:
org.licenses_on_owned_dongles.where(conditions)
I'm trying to connect the values of two join tables that I have and show the results based on a conditional relationship...and i'm having some problems
I have a Users Model(:name, :password, :email), and Events model(:name, :etc) and Interests model (:name)
I created about 5 records in each model.
Then I created two join tables -> UsersInterests and EventsInterests; each not containing a primary key and only comprised of the user_id/interest_id and event_id/interest_id respectively.
Then I added to the model files the HABTM Relationship
users => has_and_belongs_to_many :interests
events => has_and_belongs_to_many :interests
interests => has_and_belongs_to_many :users
has_and_belongs_to_many :events
Now I wanted to create a controller that finds only the events where the users interests correspond with the events interests
From working on this for a while I've figured that I need something in the area of
#Events = Event.User.find([condition])
[condition] = where users.interest == event.interest
or something like that... I'm kind of lost..How do you state the find condition?...I know how to do the inner join in sql but I'm looking for the elegant Rails way to do this... any tips guys?
The elegant ruby way to do this is with named scopes. However because you've decided to use has_and_belongs_to_many relationships instead of has_many :through relationships, you're going to need to define the join with raw SQL, which isn't very elegant. And because of the way Rails handles SQL generation, you will have to make a scope for use with a single user, and a second named scope for use with many users.
Class Event < ActiveRecord::Base
...
#find events that share an interest with a single user
named_scope :shares_interest_with_user, lambda {|user|
{ :joins => "LEFT JOIN events_interests ei ON ei.event_id = events.id " +
"LEFT JOIN users_intersets ui ON ui.interest_id = ei.interest_id",
:conditions => ["ui.user_id = ?", user], :group_by => "events.id"
}
#find events that share an interest with a list of users
named_scope :shares_interest_with_users, lambda {|users|
{ :joins => "LEFT JOIN events_interests ei ON ei.event_id = events.id " +
"LEFT JOIN users_intersets ui ON ui.interest_id = ei.interest_id",
:conditions => ["ui.user_id IN ?", users], :group_by => "events.id"
}
}
#find events that share an interest with any user
named_scope :shares_interest_with_any_user, lambda {
{ :joins => "LEFT JOIN events_interests ei ON ei.event_id = events.id " +
"JOIN users_intersets ui ON ui.interest_id = ei.interest_id",
:conditions => "ui.user_id IS NOT NULL", :group_by => "events.id"
}
}
end
Now you can do this to get all the events a user might be interested in:
#events = Event.shares_interest_with_user(#user)
Or this to get all the events a list of users might be interested in:
#events = Event.shares_interest_with_users(#users)
But as I warned, that's not really elegant.
You can greatly simplify the joins if you redefine your relationships to be has_many through relationships with proper join models instead of HABTM relationships. Your case would require the nested has many through plugin for this to work. N.B. You'll have to add corresponding has_many/belongs_to statements in all of the other models. Even the join models.
Class Event < ActiveRecord::Base
has_many :event_interests
has_many :interests, :through => :event_interests
has_many :user_interests, :through => :interests
has_many :users, :through => :user_interests
...
#find events that share an interest with a list of users
named_scope :shares_interest_with_users, lambda {|user|
{ :joins => :user_interests, :group_by => "events.id",
:conditions => {:user_interests => {:user_id => user}}
}
}
#find events that share an interest with any user
named_scope :shares_interest_with_any_user, lambda {
{ :joins => :user_interests, :group_by => "events.id",
:conditions => "user_interests.user_id IS NOT NULL"
}
end
Now, the following will work.
#user = User.first; #users = User.find(1,2,3)
# #events = all events a single user would be interested in
#events = Event.shares_interest_with_users(#user)
# #events = all events any of the listed users would be interested in.
#events = Event.shares_interest_with_users(#user)
You could even define a named scope to select events that haven't happened yet and chain the two:
named_scope :future_events, lambda {
{ :conditions => ["start_time > ?", Time.now]}
}
Events.future_events #=> Events that haven't started yet.
# Events that a user would be interested in but only choose those
# that haven't started yet.
Events.future_events.shares_interest_with_user(#user)
I have two models, user and group. I also have a joining table groups_users.
I have an association in the group model:
has_many :groups_users
has_many :users, :through=> :groups_users
I would like to add pending_users which would be the same as the users association but contain some conditions. I wish to set it up as an association so that all the conditions are handled in the sql call. I know there's a way to have multiple accessors for the same model, even if the name is not related to what the table names actually are. Is it class_name?
Any help would be appreciated, thanks
Use named_scopes, they're your friend
Have you tried using a named_scope on the Group model?
Because everything is actually a proxy until you actually need the data,
you'll end up with a single query anyway if you do this:
class User < ActiveRecord::Base
named_scope :pending, :conditions => { :status => 'pending' }
and then:
a_group.users.pending
Confirmation
I ran the following code with an existing app of mine:
Feature.find(6).comments.published
It results in this query (ignoring the first query to get feature 6):
SELECT *
FROM `comments`
WHERE (`comments`.feature_id = 6)
AND ((`comments`.`status` = 'published') AND (`comments`.feature_id = 6))
ORDER BY created_at
And here's the relevant model code:
class Feature < ActiveRecord::Base
has_many :comments
class Comment < ActiveRecord::Base
belongs_to :feature
named_scope :published, :conditions => { :status => 'published' }
This should be pretty close - more on has_many.
has_many :pending_users,
:through => :groups_users,
:source => :users,
:conditions => {:pending => true}
:pending is probably called something else - however you determine your pending users. As a side note - usually when you see a user/group model the association is called membership.
In the User model:
named_scope :pending, :include => :groups_users, :conditions => ["group_users.pending = ?", true]
That's if you have a bool column named "pending" in the join table group_users.
Edit:
Btw, with this you can do stuff like:
Group.find(id).users.pending(:conditions => ["insert_sql_where_clause", arguments])
I have the following models:
class Person < ActiveRecord::Base
has_many :images
has_one :preference
end
class Image < ActiveRecord::Base
belongs_to :person
end
class Preference < ActiveRecord::Base
belongs_to :person
end
I am trying to fetch all images that are public and at the same time eager load the people who own those images:
Image.find(:all, :conditions => ["images.person_id = ? AND preferences.image_privacy = ?", user.id, PRIVACY_PUBLIC],
:joins => [:person => :user_preference], :include => :person)
It appears Rails does not like the :include (I believe because :person is referenced in 2 models). This is the error I get (which disappears when I drop the :include option):
"ActiveRecord::StatementInvalid: Mysql::Error: Not unique table/alias: 'people'"
I can get around this by writing out the actual JOIN command as a string and passing it into the :include option, but this not Rails-y so I was hoping there's a cleaner way to do this.
Any help would be much appreciated.
Thanks!
It looks like you call it "preferences", and not user_preferences. So you join should be:
:joins => [:person => :preference])
By using JOIN you are actively including the People table, so you shoudn't need to add "include" again. This should work:
Image.find(:all, :conditions => ["images.person_id = ? AND preferences.image_privacy = ?", user.id, PRIVACY_PUBLIC],
:joins => [:person => :user_preference])
It might be the issue with Table Aliasing, rails doc has great details in Table Aliasing
also, post SQL here will be useful too.
You wrote :conditions => ["images.person_id", user.id] and you said that you want to load images and people who owns those images. But it looks like you are loading images that belongs to one person (not to group of people), because you specify only one user.id.
I would do it this way:
Person.find(user.id, :include => [:images, :preference], :conditions => ["preferences.image_privacy = ?", PRIVACY_PUBLIC])
It will load person and his/her images.
Probably I don't understand your problem correctly, because what I think you want to do doesn't seem logic to me.
Instead of using conditions you can try named_scope