我正在开发一个需要 has_and_belongs_to_many 关系的项目。
这涉及拥有许多“提案”的用户和属于许多用户的提案。
这很重要,因为用户可以创建提案并邀请其他用户加入。
我无法正确设置,已阅读许多其他教程和 SO 问题,但无法对其进行排序。
这是我到目前为止所拥有的。
User.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :proposals
.......
Proposal.rb
class Proposal < ActiveRecord::Base
has_and_belongs_to_many :users
...
database migration for HABTM
class CreateProposalUserJoinTable < ActiveRecord::Migration
def change
create_table :proposals_users, :id => false do |t|
t.integer :user_id
t.integer :proposal_id
end
end
end
/views/proposals/_form.html.erb
...
<%= f.collection_select(:users, User.all, :id, :trading_name) %>
<%= f.collection_select(:users, User.all, :id, :trading_name) %>
<%= f.collection_select(:users, User.all, :id, :trading_name) %>
...
这是我希望用户选择三个用户并将它们添加到关系中的地方。
我尝试将此逻辑添加到控制器,但无法使其正常工作。
最初我将它与 id 作为外键一起破解,但想使用活动记录关联。
[编辑]
proposals_controller.rb
def create
@proposal = Proposal.new(params[:proposal])
if current_user
@user = current_user
@proposal.creator_id = @user.id
@proposal.cost = 10
end
respond_to do |format|
if @proposal.save
(params[:proposal][:users]).each do |user|
if user.to_i.to_s == user || user.to_f.to_s == user
puts user
puts "********************\n\n\n\n\n\n\n"
@proposal.users = User.find(user)
User.find(user).proposals << @proposal
end
end
@proposal.save
format.html { redirect_to @proposal, notice: 'proposal was successfully created.' }
format.json { render json: @proposal, status: :created, location: @proposal }
else
format.html { render action: "new" }
format.json { render json: @proposal.errors, status: :unprocessable_entity }
end
end
end