将rails分组的集合选择为联接表

时间:2018-08-25 19:23:22

标签: ruby-on-rails

我正在为“审阅”模型创建表单,并且尝试与教授及其所教课程一起生成嵌套的选择标签。

通过“提供”联接表,教授与课程之间的关联是多对多的。

评论属于商品,我想在嵌套的select标签中获取商品的ID。

这是我的模特:

class Professor < ApplicationRecord
  has_many :offerings, :dependent => :destroy
  has_many :courses, :through => :offerings
  has_many :reviews, :through => :offerings
end

class Course < ApplicationRecord
  has_many :offerings, :dependent => :destroy  
  has_many :professors, :through => :offerings
end

class Offering < ApplicationRecord
  belongs_to :professor
  belongs_to :course
  has_many :reviews
end

class Review < ApplicationRecord
  belongs_to :offering
  belongs_to :user
end

这是“评论”表单:

<%= form_with(model: review, local: true) do |form| %>
<%= render 'shared/error_messages', locals: {resource: review} %>

<div class="form-group">
  <%= form.label :body %>
  <%= form.text_area :body, id: :review_body, class: 'form-control' %>
</div>

<div class="form-group">
  <%= form.label :teaching_rating %>
  <%= form.range_field :teaching_rating, in: 1..5, id: :review_teaching_rating, class: 'form-control slider' %>
</div>

<div class="form-group">
  <%= form.label :offering %>
  <%= form.grouped_collection_select :offering_id, Professor.order(:name), :courses, :name, :id, :name, class: 'form-control' %>
</div>

<div class="actions">
  <%= form.submit "Submit", class: "btn btn-primary" %>
</div>
  

我应该将什么作为option_key_method参数传递给grouped_collection_select方法,以正确获取产品密钥?

如果有更好的方法,例如为教授和课程使用两个单独的下拉列表(选择教授时会更新课程列表),或者使用其他collection或其他方法,请提出建议。我是新手。

0 个答案:

没有答案