因此,在长时间努力寻找可以帮助我们的信息之后,我们发现很难找到我们可以使用的答案。
我们的问题是我们有两个表通过称为 Schools 和 Organizations 的 HABTM 关系连接起来。首先创建一个学校,然后一个组织获取学校列表,允许用户选择一个,然后使用 school_id 和组织 ID 填充第三个表 OrganizationsSchools。
三者的模型如下: 学校模型:
class School < ActiveRecord::Base
has_and_belongs_to_many :organizations, :join_table => 'organizations_schools'
attr_accessible :name
validates :name, :presence => true
end
组织模式:
class Organization < ActiveRecord::Base
has_many :materials
has_many :users
has_and_belongs_to_many :causes
has_and_belongs_to_many :schools, :join_table => 'organizations_schools'
attr_accessible :name, :unlogged_books_num, :id
validates :name, :presence => true
end
组织形式:
<%= form_for(@organization) do |f| %>
<% if @organization.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@organization.errors.count, "error") %> prohibited this organization from being saved:</h2>
<ul>
<% @organization.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% @schools = School.all %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :unlogged_books_num %><br />
<%= f.number_field :unlogged_books_num %>
</div>
<div class="field">
<%= f.label 'School' %><br />
<% school_id = nil %>
<%= collection_select(nil, school_id, @schools, :id, :name) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
最后,我们的 Organizations 控制器中的 create 函数
class OrganizationsController < ApplicationController
.
.
.
def create
@organization = Organization.new(params[:organization])
org_id = @organization.id
school_id = @organization.school_id
@org_school = OrganizationsSchool.create(:organization_id => org_id, :school_id => school_id)
respond_to do |format|
if @organization.save
format.html { redirect_to @organization, notice: 'Organization was successfully created.' }
format.json { render json: @organization, status: :created, location: @organization }
else
format.html { render action: "new" }
format.json { render json: @organization.errors, status: :unprocessable_entity }
end
end
end
end
我们的控制器中的所有其他功能都是安静地创建的。还请知道我不是最擅长数据库的人,虽然我对 Rails 很熟悉,但我一点也不擅长使用它。