0

因此,在长时间努力寻找可以帮助我们的信息之后,我们发现很难找到我们可以使用的答案。

我们的问题是我们有两个表通过称为 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 很熟悉,但我一点也不擅长使用它。

4

1 回答 1

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关系,您的控制器代码将需要额外的更改

于 2013-06-11T21:35:43.147 回答