0

has_and_belongs_to_many 관계가 필요한 프로젝트 작업 중입니다.Rails HABTM 다중 폼 요소와의 관계

많은 사용자에게 속한 "제안서"와 제안서가 많은 사용자가 여기에 해당됩니다.

사용자가 제안서를 만들고 다른 사용자를 초대 할 수 있기 때문에 중요합니다.

올바르게 설정하는 데 문제가 있습니다. 다른 많은 튜토리얼 및 기타 질문을 읽었지만 정렬 할 수 없습니다.

여기까지 제가 지금까지 있습니다.

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 
+0

콘솔에서 제대로 작동하지만 결국 collection_select에 문제가 있습니다. 사용자 ID가 아니라 사용자를 반환해야합니다 ... 매개 변수가 충돌 할 때 사용자 모델이 필요할 때 매개 변수에 사용자 => 1 (사용자 ID 1)이 있습니다. – JamesWatling

+0

하지만 사용자의 값을 할당하기 위해 숨겨진 필드를 추가하더라도 (id == 1)이 오류가 발생합니다. 정의되지 않은 메서드 'each'for "# ": String – JamesWatling

답변

3

제안에 사용자를 할당 할 필요는 없습니다. 대신, 당신은 또한이 같은 ID를 할당 할 수

proposal.user_ids = params[:proposal][:user_ids] 

를 코드를 다음에서 할당이 자동으로 수행됩니다 :

proposal.attributes = params[:proposal] 

이 일을하려면, 뷰는 다음과 같이 변경해야합니다 :

<%= select_tag("proposal[user_ids][]", options_from_collection_for_select(User.all, :id, :trading_name)) %> 
+0

이 응답을받습니다. 위와 같이 변경 : 'NoMethodError in ProposalsController # create 정의되지 않은 메소드'proposals 'for # ' – JamesWatling

+0

ProposalsController # create의 코드를 보여줄 수 있습니까? – Yanhao

+0

위의 편집 확인 – JamesWatling