I do this:
user.events
This is a proper AR query, you can chain it with other scopes and stuff:
user.events.where(<your event conditions here>)
EDIT: AFAIK the other way around you must specify both fields (makes sense: you could have a user with id 4 and another thing with events, like a Party, also with id 4).
EDIT2: Regarding "Why does create
work and where
doesn't": create
is more highlevel than where
, because the former deals with "a complete model", while the latter manages things at the database table level.
- ActiveRecord's
create
(AFAIK) uses a combination of new
+ update_param
somewhere down the line.
update_param
uses your model's xxxx=
methods for assigning each individual property.
- In your example,
historizable=
is a method built by the belongs_to
expression. Since the belongs_to
"knows" that it's polymorphic, it can deal with the type and id.
On the other hand, when you pass a hash to the where
clause, the parameters there only refer to database fields. Rails provides scopes for "higher level" access:
class Event < ActiveRecord::Base
...
scope :by_historizable, lambda { |h| where(:historizable_id => h.id, :historizable_type => h.class.name) }
end
...
Event.by_historizable(user).where(<your other queries here>)
I've heard that this might change in Rails 4, and where
might be more "intelligent". But I have not checked yet.
user.events
if I have thehas_many
properly configured but I'm looking for thewhere
possibility. – Allhallows