Rails从多个表中选择为select字段创建集合?

时间:2013-11-28 17:39:20

标签: ruby-on-rails select

我正在尝试动态构建一个集合,其中每个数组都包含两个独立表中的值。

模特:

#/models/user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :user_id, :email, :password, :password_confirmation, :remember_me,
  :first_name, :last_name, :permanent_address, :permanent_city,
  :permanent_state, :permanent_zip, :home_phone, :mobile_phone, :role,
  :tenant_attributes, :rents_attributes

  validates :email, :presence => true, :uniqueness => true
  validates :first_name, :presence => true
  validates :last_name, :presence => true
  validates :permanent_address, :presence => true
  validates :permanent_city, :presence => true
  validates :permanent_zip, :presence => true
  validates :first_name, :presence => true
  validates :home_phone, :presence => true

  has_one :app
  has_one :tenant, :foreign_key => :users_id
  has_many :rents
  has_many :maints

  accepts_nested_attributes_for :tenant
  accepts_nested_attributes_for :rents, allow_destroy: true

end

#/models/tenant.rb

class Tenant < ActiveRecord::Base
  belongs_to :users
  belongs_to :units
  attr_accessible :lease_begin, :lease_end, :rent_share, :users_id, :units_id

  has_many :maints

end

助手方法(到目前为止):

#/helpers/users_helper.rb

def tenants 

  tenants = Tenant.select([:id, ??? ])

  tenants.map {|u| [u.???, u.id]}

end

表单字段:

<%= f.input :tenant_id, :collection => tenants %>

基本上我要做的是从Tenants表中选择:id,然后从Users表中选择关联的:first_name +:last_name(由上面的“???”表示)来填充集合数组产生

这里最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

如果您的帮助程序专门用于此input,那么我相信您对查询有正确的想法,因为您只关心检索所需的列。

要从tenant关系中检索包含属性的belongs_to :user,您的帮助程序定义需要更新为:

# app/helpers/users_helper.rb
def tenants 
  tenants = Tenant.joins(:user).select('tenants.id as tenant_id, users.first_name, users.last_name')
  tenants.map { |u| [ [u.first_name, u.last_name].join(' '), u.tenant_id ]}
end

然后tenants帮助器返回一个first_namelast_name的嵌套数组,其中空格作为一个元素,tenant_id作为第二个元素数组。

使用更新的帮助程序,您的视图将是:

<%= f.select :tenant_id, :collection => tenants %>

注意在这里使用select助手更适合这种情况。