Department モデル、Course モデル、および Mandatory モデルがあります。各部門には必須のコースがいくつかあるため、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