Ruby on rails Rails从多个表中选择以创建选择字段的集合?
我试图动态构建一个集合,其中每个数组包含来自两个单独表的值 模型:Ruby on rails Rails从多个表中选择以创建选择字段的集合?,ruby-on-rails,select,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, :register
#/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
表单字段:
<%= f.input :tenant_id, :collection => tenants %>
租户%>
基本上,我要做的是从租户表中选择:id,然后从用户表中选择关联的:first_name+:last_name(上面用“?”表示),以填充将生成的集合数组
这里最好的方法是什么?如果您的助手专门用于此
输入
,那么我相信您对查询的想法是正确的,因为您只关心检索所需的列
要检索租户
s(包括其所属的属性)\u 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\u name
和last\u name
以空格作为一个元素,以tenant\u id
作为第二个元素数组
使用更新的帮助器,您的视图将是:
<%= f.select :tenant_id, :collection => tenants %>
租户%>
注意这里使用的helper更适合这种情况
<%= f.select :tenant_id, :collection => tenants %>