【发布时间】:2014-01-16 07:19:57
【问题描述】:
我希望在这里得到一些很大的帮助。我在 Rails 3.2 的许多领域都是菜鸟,但我正在变得更好。
我有一个已检索到正确记录的集合选择。我有多个属性,然后有多个用户。集合选择正确地使用 UserProperty 表仅过滤属性用户(我希望集合显示与该属性相关的每个用户)。所以我有用户 ID 而不是名字。
所以我尝试通过查询父表(用户)来创建一个对象以提取父属性并通过。不幸的是,第二个查询只传递了一条记录。所以放弃了。
最简单的方法是在 collection_select 中使用第一个查询,然后根据参考用户 ID 显示父字段。是否有允许我在集合选择和查询对象“池”中将文本显示回父 (USER) 表的语法?
目标是通过嵌套路由(@property)查询 UserProperties - 工作。 (@pool 包含正确的结果)
然后显示来自用户的名称字段。 (用户名)
这是我的代码:
控制器:
def find_property
@property = Property.find(params[:property_id])
@pool = UserProperty.find_all_by_property_id(@property)
end
查看:
<%= fields_for (:assigned_to_user_id) do |pool| %>
<%= pool.collection_select(:assigned_to_user_id, @pool, :id, :id ) %>
<!-- Need to change last field from id to name field of Users Table -->
模型设计:(需要用户名)
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
class User < ActiveRecord::Base
attr_accessible :name, :email
has_many :properties, through: :user_properties
end
# Table name: user_properties
#
# id :integer not null, primary key
# user_id :integer
# property_id :integer
class UserProperty < ActiveRecord::Base
attr_accessible :property_id, :user_id
belongs_to :user
belongs_to :property
end
【问题讨论】:
-
不要在标题中写“已解决”。相反,使用旁边的大复选标记按钮将可接受的答案标记为已接受。
标签: ruby-on-rails ruby-on-rails-3.2 parent-child grouped-collection-select