2013-12-18 49 views
0

我想要使用Has並且屬於很多關係來將用戶鏈接到團隊,我遇到的問題是我無法計算出如何將id添加到我的user_teams表中。Ruby on Rails HABTM在表格中添加記錄

在我的模型我已經做了以下

用戶模型

has_and_belongs_to_many :teams 

團隊模型

has_many :users 

隊控制器

def create 
    @team = Team.new(params[:team]) 

    respond_to do |format| 
     if @team.save 
     @team.users << User.find(current_user) 
     format.html { redirect_to @team, notice: 'Team was successfully created.' } 
     format.json { render json: @team, status: :created, location: @team } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @team.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

回答

1

你沒有適當的關係。你應該照顧協會的habtm遷移,看一看,以下面的例子,我有兩個模式「用戶」和「組織」

組織模式

class Organization < ActiveRecord::Base 
    has_and_belongs_to_many :users, 
     :association_foreign_key => 'user_id', 
     :class_name => 'User', 
     :join_table => 'organizations_users' 
    attr_accessible :address, :name 
end 

用戶模型

class User < ActiveRecord::Base 
    has_and_belongs_to_many :organizations, 
    :association_foreign_key => 'organization_id', 
    :class_name => 'Organization', 
    :join_table => 'organizations_users' 
    attr_accessible :name, :phone 
end 

然後需要像下面那樣創建新的OrganizationsUsers遷移。

class CreateOrganizationsUsersTable < ActiveRecord::Migration 
    def self.up 
    create_table :organizations_users, :id => false do |t| 
     t.references :organization 
     t.references :user 
    end 
    add_index :organizations_users, [:organization_id, :user_id] 
    add_index :organizations_users, [:user_id, :organization_id] 
    end 

    def self.down 
    drop_table :organizations_users 
    end 
end 

您可以從here得到工作示例。

+0

夢幻般的迴應,它已經清除了堆如何設置遷移和關係 –

+0

我很高興,它幫助你。 –