我遇到了简单形式的关系数据问题。到目前为止,“集合”在表单中运行良好,但我无法弄清楚如何正确使用“label_method”:
<%= f.input :participation_id, collection: Participation.where(user_id: current_user.id), as: :select, label_method: "????", label: 'Choose' %>
我想使用我的“考试”模型中的“考试”名称。我可以在控制台中从模型中检索它:
p = Participation.where(user_id: 1)
p.first.examination.name
但是你可能会猜到它会返回多个值,因为对于ID为1的用户我有3个不同的参与,并且每个参与都有不同的考试名称。
如何在每次参加“label_method”时检索每个考试的名称?
感谢。
new.html.erb =&gt;
<%= simple_form_for(@order, html:{class: "well"}, :url => "https://somewhere.com", :method => :post) do |f| %>
<%= f.input :participation_id, collection: Participation.where(user_id: current_user.id), as: :select, label_method: "????", label: 'Choose' %>
<%= f.input :user_id, as: :hidden, input_html: { value: current_user.id } %>
<%= f.button :submit %>
<% end %>
我的模特=&gt;
class Participation < ActiveRecord::Base
belongs_to :user
belongs_to :examination
has_one :order
end
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :participation
end
class Examination < ActiveRecord::Base
has_many :participations
has_many :users, :through => :participations
end
数据库结构=&gt;
create_table "examinations", force: true do |t|
t.string "name"
t.string "shortname"
t.datetime "exam_date"
end
create_table "participations", force: true do |t|
t.integer "user_id"
t.integer "examination_id"
t.string "language_preference"
t.string "exam_center_preference"
end
create_table "orders", force: true do |t|
t.string "first_name"
t.string "last_name"
t.integer "participation_id"
t.integer "user_id"
end
答案 0 :(得分:1)
尝试一次:
p = Participation.where(user_id: 1)
<%= f.input :participation_id, collection: Participation.where(user_id: current_user.id), as: :select, label_method: lambda{|x| x.examination.name}, label: 'Choose' %>