2013-11-28 52 views
0

我想動態地建立一個集合,其中每個數組包含來自兩個獨立表的值。Rails從多個表中選擇爲選擇字段創建集合?

型號:

#/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

如果你的幫手專門用於這個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幫助其更適合於這種情況。