0

我有部门模型、课程模型和必修模型。每个系都有一些必修课,所以我使用 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
4

2 回答 2

1

您需要在如下形式的上下文中使用它:

<% form_for @mandatory do |f| %>

  <div class="field">
    <%= f.label :course_id %><br />
    <%= f.collection_select(:course_id, Course.all, :id, :name) %>
  </div>

  <%= f.submit %>
<% end %>
于 2013-08-13T13:03:30.313 回答
1
<%= collection_select(:person, :city_id, City.all, :id, :name) %>

让我们看一下部分:

:person是包含集合中一项的模型的名称。

:city_id是模型中包含集合中项目的字段的名称。

City.all是集合中的项目列表。@cities如果您在控制器 ( ) 中执行数据库请求,这可能是一个实例变量 ( @cities = City.all)。如果您在集合中只需要这些记录,您也可以只获取记录的子集 ( @cities = City.where("state = ?", ["NY", "SC", "NE"]))

:id并且是选择列表中每一行中使用:name的对象中的字段。是值,是下拉列表中每个选项的文本。City:id:name

生成的 HTML 应如下所示

<select name="person[city_id]">
<option value="1">New York</option>
<option value="3">Rome</option>
<option value="4">Charleston</option>
<option value="17">Omaha</option>
</select>

编辑:当我不看的时候,select 中的 'id' 似乎已经退出了,所以我把它删除了。

于 2013-08-13T13:30:21.643 回答