Rails 3 - select with Include?

核能气质少年 提交于 2019-12-17 06:34:11

问题


Here is a nested select with include:

@items = Item.where("complete = ?", true).includes( :manufacturer, {:order=>[:supplier, :agent] })

This is a taxing query as it pulls 1000s of rows of data from all the above included tables.

How can I get the query to only select specific fields?

  • user.name, user.created_at
  • order.created_at
  • supplier.name
  • agent.name
  • manufacturer.name

回答1:


There is a select method in ARel, but you must use the correct table names (i.e. plural and beware if you have polymorphic models or if you're using set_table_name or some other similar non-standard practice)

@items = Item.
  select('users.name', 'users.created_at', 'orders.created_at', 'suppliers.name', 'agents.name', 'manufacturers.name').
  where(:users => { :fulfilled => true }).
  includes(:orders => [:supplier, :agent], :manufacturer)

"We can use select with joins not includes" - @Bhavesh_A_P

Note:

As @Bhavesh_A_P pointed out above, select with includes does not produce consistent behavior. It appears that if the included association returns no results, select will work properly, if it returns results, the select statement will have no effect. In fact, it will be completely ignored, such that your select statement could reference invalid table names and no error would be produced. select with joins will produce consistent behavior.




回答2:


Actually we can't use select with includes. It can only be used with joins.




回答3:


The problem is not solved by including a call to the 'select' method in the chain. In a similar ActiveRecord::Relation we built, calling 'includes' seems to override any call to 'select'.

scope :active, where("hired_on < ? AND (separated_on > ? OR separated_on IS NULL)", Time.now, Time.now )

scope :with_role, lambda {|roles| includes(:team_member_roles).where(:team_member_roles => {:role => roles } ) }

scope :with_site_code, lambda {|site_codes| includes(:team_member_sites).where(:team_member_sites => {:site_code => site_codes } ) }

TeamMember.select("team_members.email, team_members.first_name, team_members.last_name").active.with_site_code(params[:site_code]).with_role(["senior_editing", "senior_and_reg_editing"]) 

As shown, the query selects all columns.

When the 2 scopes use 'joins' instead of 'includes', the query works: only the 3 specified columns are selected.




回答4:


Item.where("fulfilled = ?", true)
    .includes({:orders =>[:suppliers, :agents]}, :manufacturers)
    .select("users.name, users.created_at, orders.created_at, suppliers.name, agents.name").
    .order('orders.created_at DESC')


来源:https://stackoverflow.com/questions/4047833/rails-3-select-with-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!