使用3列连接表创建/编辑

时间:2011-02-15 17:00:06

标签: ruby-on-rails database join

正如之前的帖子要求(Alias table name to facilitate 3 column join table (MySQL or PostgreSQL)),我正在开发一个连接表,连接3个表,Project,Employee,Role。使用:join_table =>当我想显示来自连接表的信息时,“my_join_table”工作正常。但是,在create操作期间,插入SQL请求的次数是两次:

INSERT INTO properties_roles_users (project_id, employee_id) VALUES (11, 14)
and 
INSERT INTO properties_roles_users (role_id, project_id) VALUES (5, 11)

而不是只有一个插入3个字段。

我使用habtm关系。

任何想法如何获得具有所有三个ID(employee_id,project_id,role_id)的INSERT INTO?

[编辑] 好吧,我正在使用其他帖子的部分代码,所以在上下文中有意义......然后我们应该读取“employees_projects_roles”。任何人,让我说我会继续用户,财产和角色。这是我的观点中的代码:

<% form_for(@property,:html => { :multipart => true }) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :address %><br />
    <%= f.text_field :address %>
  </p>
  ( ... code ... )

  <p>
    <%= f.label :role, 'Role' %><br />
    <%= f.collection_select :role_ids, Role.find(:all, :order => 'role'), :id, :role, {}, :multiple => true %>
  </p>

      <%= f.hidden_field :user_ids, :value => current_user.id %>

  <%= render :partial => 'form', :locals => { :f => f } %>

  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

Controller(properties_controller:

def创建     @property = Property.new(params [:property])

respond_to do |format|
  if @property.save
    flash[:notice] = 'Property was successfully created.'
    format.html { redirect_to(@property) }
    format.xml  { render :xml => @property, :status => :created, :location => @property }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @property.errors, :status => :unprocessable_entity }
  end
end

型号:

class User < ActiveRecord::Base
  has_and_belongs_to_many :properties, :join_table => "properties_roles_users"
  has_and_belongs_to_many :roles, :join_table => "properties_roles_users"
  (... other useful stuff ...)
end

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => "properties_roles_users"
  has_and_belongs_to_many :properties, :join_table => "properties_roles_users"
end

class Property < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => "properties_roles_users"
  has_and_belongs_to_many :roles, :join_table => "properties_roles_users"

  attr_accessible (...:different_fields...) :user_ids, :role_ids
end

1 个答案:

答案 0 :(得分:1)

知道了。看来我需要在habtm声明中编写一个:insert_sql语句,例如:

has_and_belongs_to_many :users, 
:join_table => "projects_roles_users",
:foreign_key => 'role_id',
:association_foreign_key => 'project_id',
:insert_sql => 'INSERT INTO
            projects_roles_users(project_id,role_id,user_id) 
            VALUES(#{id}, #{role_ids}, #{user_ids})'