我有部门模型、课程模型和必修模型。每个系都有一些必修课,所以我使用 Mandatory 模型来映射 Courses 和 Department 模型。
我希望能够通过选择课程和部门的名称而不是他们的 ID 来创建“强制性”关系。
我想我会创建 2 个实例变量 @departments(Department.all) 和 @courses(Course.all) 并在视图中将它们显示为下拉列表,因此您选择 1 个部门、1 个课程并创建强制关系。事实证明它并不像我希望的那么简单。我不明白我应该如何使用collection_select
辅助方法。我已阅读文档,但我不明白。
所以我的部门模型是
class Department < ActiveRecord::Base
attr_accessible :industry_name, :name
has_many :employees
has_many :mandatories
has_many :courses, :through => :mandatories
end
课程模式
class Course < ActiveRecord::Base
attr_accessible :name
has_many :registrations
has_many :mandatories
has_many :employees, :through => :registrations
has_many :departments, :through => :mandatories
end
强制模型
class Mandatory < ActiveRecord::Base
attr_accessible :course_id, :department_id
belongs_to :course
belongs_to :department
end
我从文档中得到的语法是<%= collection_select(:person, :city_id, City.all, :id, :name) %>
完全不明白这一点。
编辑::
所以,这是我目前的看法。我还没有collection_select
。现在要在部门和课程之间建立关系,我需要输入他们不想做的 ID。我想要一个带有部门名称和课程名称的下拉列表。
这是我_form.html
的强制控制器
<%= form_for(@mandatory) do |f| %>
<% if @mandatory.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@mandatory.errors.count, "error") %> prohibited this mandatory from being saved:</h2>
<ul>
<% @mandatory.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :department_id %><br />
<%= f.number_field :department_id %>
</div>
<div class="field">
<%= f.label :course_id %><br />
<%= f.number_field :course_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
这是强制控制器
def create
@mandatory = Mandatory.new(params[:mandatory])
@courses = Course.all
@departments =Department.all
respond_to do |format|
if @mandatory.save
format.html { redirect_to @mandatory, notice: 'Mandatory was successfully created.' }
format.json { render json: @mandatory, status: :created, location: @mandatory }
else
format.html { render action: "new" }
format.json { render json: @mandatory.errors, status: :unprocessable_entity }
end
end
end