因此,经过长时间努力寻找可以帮助我们的信息后,我们发现很难找到可以使用的答案。
我们的问题是我们有两个表通过称为学校和组织的HABTM关系加入。首先创建一所学校,然后一个组织获取学校列表,允许用户选择一个,然后使用school_id和organization_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 %>
最后,我们的组织控制器中的创建功能
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,但我并不熟练使用它。
答案 0 :(得分:4)
在has_and_belongs_to_many中,组织不会有school_id字段。听起来你真的想要:
class Organization < ActiveRecord::Base
belongs_to :school
...
end
class School < ActiveRecord::Base
has_many :organizations
end
如果你真的想要HABTM,那么你可以写:
@organization.schools << School.find school_id
修改的:
显然,如果您转换为has_many
关系