The following query returns the collection of AR objects that I want to update:
Variant.all(:joins => { :candy_product => :candy }, :conditions => "candies.name = 'Skittles'")
I'm trying to do something like the following:
Variant.update_all(:price => 5, :joins => { :candy_product => :candy }, :conditions => "candies.name = 'Skittles'")
This should only update the price for the variants returned from original query. Is this possible with AR or will I have to write the SQL? This is a pretty large collection, so anything that iterates is out.
Using Rails 2.3.4.
As #François Beausoleil pointed correctly we should use scoped
Variant.scoped(:joins => { :candy_product => :candy }, :conditions => "candies.name = 'Skittles'").update_all(:price => 5)
Related
I try to run query like this with Nhibernate v.4:
Select o.Number, c.Address
From Order o join Client c on o.ClientId = c.Id
Where c.Name = "John"
Tried many ways to do that with JoinQueryOver and JoinAlias but nothing helps, endup with error "could not resolve property: Address of Order"
Session.QueryOver<Order>()
.JoinQueryOver(s => s.Client)
.Where(() => c.Name == "John")
.SelectList(x => .Select(Projections.Property<Order>(o => o.Number)
.SelectList(x => .Select(Projections.Property<Order>(o => o.Client.Address))
or like this
...
.SelectList(x => .Select(Projections.Property<Order>(o => o.Number)
.SelectList(x => .Select(Projections.Property<Client>(c => c.Address))
What is the right way to build the query or something very similar? Problem with 'Select' operator, 'Where' part works fine. I can also build non-join queries by this 2 entities separate from each other and it works well, but no idea how to join them
Finally I've figured out how to make it work:
Client client = null;
OrderClientDto dto = null;
var result = Session.QueryOver<Order>()
.JoinAlias(o => o.Client, () => client)
.Where(() => c.Name == "John")
.SelectList(x => x
.Select(o => o.Number).WithAlias(() => dto.Number)
.Select(() => o.Client.Address).WithAlias(() => dto.Address))
.TransformUsing(Transformers.AliasToBean<OrderClientDto>())
.List<OrderClientDto>();
Nhb is far from being intuitive and convenient. Same query is much easier to write in EF.
I want to get some object form Ad table.
I tried:
Ad.find(:all, :conditions => {:header => "1"})
and:
Ad.find(:all, :conditions => ["header=?", "1"])
but return a empty array.
when i try Ad.all I see Objects which match to my conditions
can you help me?
If you are on Rails 3.0, you should be using the new Arel syntax:
Ad.where(:header => "1")
Check out http://guides.rubyonrails.org/active_record_querying.html and http://asciicasts.com/episodes/202-active-record-queries-in-rails-3 for more info
I'm using NHibernate 3.0 with both the LINQ provider and QueryOver. Sometimes I want to eager load related data, and there comes the method "Fetch" to the rescue, both in LINQ and QueryOver. Now I have a special scenario where I want to eager load a property not directly on the second level, like:
Foo f = ...;
f.A.B.C
with LINQ there's no problem, as you can "chain" fetches with the method "ThenFetch", like:
var result = Session.Query<Foo>().Fetch(a => a.A).ThenFetch(b => b.B).ThenFetch(c => c.C).ToList();
In QueryOver there's no such method, so how can I achieve the same result?
Thanks in advance.
I actually managed to solve this problem using two different approaches:
Approach one:
Session.QueryOver<Foo>().Fetch(x => x.A).Fetch(x => x.A.B).Fetch(x => x.A.B.C)
Approach two:
A a = null;
B b = null;
C c = null;
Session.QueryOver<Foo>()
.JoinAlias(x => x.A, () => a)
.JoinAlias(() => a.B, () => b)
.JoinAlias(() => b.C, () => c)
Both work (altough I'm not exactly sure if one of them generated "inner" and the other one "outer" joins).
Just as a curiosity, I'll post the reply they gave me on the NHibernate Jira:
query
.Fetch(p => p.B)
.Fetch(p => p.B.C) // if B is not a collection ... or
.Fetch(p => p.B[0].C) // if B is a collection ... or
.Fetch(p => p.B.First().C) // if B is an IEnumerable (using .First() extension method)
I think you can do that with JoinQueryOver
IQueryOver<Relation> actual =
CreateTestQueryOver<Relation>()
.Inner.JoinQueryOver(r => r.Related1)
.Left.JoinQueryOver(r => r.Related2)
.Right.JoinQueryOver(r => r.Related3)
.Full.JoinQueryOver(r => r.Related4)
.JoinQueryOver(r => r.Collection1, () => collection1Alias)
.Left.JoinQueryOver(r => r.Collection2, () => collection2Alias)
.Right.JoinQueryOver(r => r.Collection3)
.Full.JoinQueryOver(r => r.People, () => personAlias);
I'm trying to load all the collections eagerly, using NHibernate 3 alpha 1. I'm wondering if this the right way of using ThenFetch()?
Properties with plural names are collections. The others are just a single object.
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi).Fetch(mi => mi.Milestone)
.ThenFetch(m => m.PrimaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.SecondaryOwners)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Predecessors)
.Fetch(mi => mi.Milestone)
.ThenFetch(m => m.Function)
.Fetch(mi => mi.Milestone)
.ThenFetchMany(m => m.Jobs)
.ThenFetch(j => j.Source)
;
I thought of asking this in the NHibernate forums but unfortunately access to google groups is forbidden from where I am. I know Fabio is here, so maybe the guys from the NHibernate team can shed some light on this?
Thanks
Apparently, there's no "right" way to use ThenFetch in such a case. Your example works fine but SQL produced contains many joins to Milestone, which isn't that right.
Using IQueryOver instead of IQueryable allows you to use complex syntax in Fetch:
Fetch(p => p.B)
Fetch(p => p.B.C) // if B is not a collection ... or
Fetch(p => p.B[0].C) // if B is a collection ... or
Fetch(p => p.B.First().C) // if B is an IEnumerable (using .First() extension method)
So in your case it would be:
query // = session.QueryOver<X>()
.Fetch(mi => mi.Milestone).Eager
.Fetch(mi => mi.Milestone.PrimaryOwners).Eager
.Fetch(mi => mi.Milestone.SecondaryOwners).Eager
.Fetch(mi => mi.Milestone.Predecessors).Eager
.Fetch(mi => mi.Milestone.Function).Eager
.Fetch(mi => mi.Milestone.Jobs).Eager
.Fetch(mi => mi.Milestone.Jobs.First().Source).Eager
The one thing you are missing is that you should use FetchMany() and ThenFetchMany() is the child property is a collection.
IQueryable<T> milestoneInstances = Db.Find<T, IQueryable<T>>(db =>
from mi in db
where mi.RunDate == runDate
select mi);
var fetch = milestoneInstances.Fetch(f => f.Milestone);
fetch.ThenFetch(f => f.PrimaryOwners);
fetch.ThenFetch(f => f.SecondaryOwners);
//...
As leora said, make sure when fetching children collections that you use
FetchMany()
ThenFetchMany()
A new Fetch, should pick up from the root, but this does not always happen. Sometimes you need to create them as separate queries or use Criteria Futures to batch up a multiple fetch.
I have a an method that retrieves Groups that are present in certain areas. Groups are given a country_id, region_id and city_id
The UI gives three select boxes to choose a country, a region from that country and then a city from that region. To find all groups in a particular city, I have this code:
#groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
This all works fine, but I also want it to find all groups in an area when the lower criteria isn't specified. For example, If a country and region are given, but not city, I'd like to find it by the region.
What I'm doing is this:
if !params[:city_id].nil?
#groups = Group.find(:all, :conditions => {:city_id => params[:city_id]})
else
if !params[:region_id].nil?
#groups = Group.find(:all, :conditions => {:region_id => params[:region_id]})
else
#groups = Group.find(:all, :conditions => {:country_id => params[:country_id]})
end
end
This works perfectly well, but it seems like it's a little inefficient. Am I doing it the best way or can I streamline a little?
One idea I had was to have a single find checking against all parameters, but I could not work out how to effectively 'ignore' parameters that were nil - my main thought was to check which ones were not set and set them to something like '*' or 'true', but that's not how SQL plays the game.
Sounds like a job for named scopes:
class Group < ActiveRecord::Base
named_scope :in_city, lambda { |city_id| {
:conditions => { :city_id => city_id }
}}
named_scope :in_region, lambda { |region_id | {
:conditions => { :region_id => region_id }
}}
named_scope :in_country, lambda { |country_id | {
:conditions => { :country_id => country_id }
}}
end
This establishes some simple scopes for restricting the Group records. Presumably you have indexed your database properly so these are quick to resolve.
The controller is much easier to implement then:
def index
#group_scope = Group
if (!params[:city_id].blank?)
#group_scope = #group_scope.in_city(params[:city_id])
elsif (!params[:region_id].blank?)
#group_scope = #group_scope.in_region(params[:region_id])
elsif (!params[:country_id].blank?)
#group_scope = #group_scope.in_country(params[:country_id])
end
#groups = #group_scope.all
end
Generally you should be testing for .blank? instead of .nil? as some form elements can send in empty results, such as a select with something akin to "All" as the default.
You could use some Ruby idioms to get something a little more succinct.
Try something like this: (untested code!)
def index
#groups = Group.find :all, :conditions => [:city_id, :region_id, :country_id].inject {} do |conditions, name|
conditions[name] = params[name] unless params[name].blank?
conditions
end
end
If every value in params is a candidate for :conditions you can just do this:
#groups = Group.all(:conditions => params.reject { |idx, val| val.nil? })
This just throws out nil values from params and uses the remaining values for conditions.
If you don't want to use all of the values in params, you have two options. You can just get rid of a bunch of redundancy in your original code:
conditions = if !params[:city_id].nil?
{ :city_id => params[:city_id] }
elsif !params[:region_id].nil?
{ :region_id => params[:region_id] }
else
{ :country_id => params[:country_id] }
end
#groups = Group.all(:conditions => conditions)
You can knock of a few more lines like this, but it sacrifices a bit of readability IMO:
conditions = if !params[:city_id].nil? then { :city_id => params[:city_id] }
elsif !params[:region_id].nil? then { :region_id => params[:region_id] }
else { :country_id => params[:country_id] }
end
Or you can do something like this:
conditions = [:city_id, :region_id, :country_id].inject({}) do |hsh, sym|
hsh[sym] = params[sym] unless params[sym].nil?
hsh
end
#groups = Group.all(:conditions => conditions)
This has the advantage that you don't need to add another condition for each symbol.