Rails 3 - select with Include?

后端 未结 4 1064
南笙
南笙 2020-11-29 02:44

Here is a nested select with include:

@items = Item.where(\"complete = ?\", true).includes( :manufacturer, {:order=>[:supplier, :agent] })
相关标签:
4条回答
  • 2020-11-29 02:54
    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')
    
    0 讨论(0)
  • 2020-11-29 02:56

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

    0 讨论(0)
  • 2020-11-29 03:09

    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.

    0 讨论(0)
  • 2020-11-29 03:11

    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.

    0 讨论(0)
提交回复
热议问题