【发布时间】:2011-06-27 18:25:49
【问题描述】:
正如之前的帖子所问的 (Alias table name to facilitate 3 column join table (MySQL or PostgreSQL)),我正在处理一个连接 3 个表的连接表,即项目、员工、角色。当我想显示来自连接表的信息时,使用 :join_table => "my_join_table" 可以正常工作。但是,在创建操作期间,插入 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 %>
控制器(properties_controller:
定义创建 @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
【问题讨论】:
-
能否请您包含用于更新您的 properties_roles_users 模型的代码?您有两个插入语句的原因是您正在创建两个单独的 properties_roles_user 对象,而不是您想要做的一个。
-
我应该为 properties_roles_users 创建一个额外的模型吗?目前,我有三个模型:属性、用户和角色。
-
所以我想问题是:如何将用户 ID 放入以链接到 collection_select 从而不使用 hidden_field?
标签: ruby-on-rails database join