Вопрос

I am trying to use a Has and belongs to many relationship to link users to teams, the issue I am having is that I cannot work out how to add the ids into my user_teams table.

In my model I have done the following

User Model

has_and_belongs_to_many :teams

Team Model

has_many :users

Teams Controller

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
Это было полезно?

Решение

You don't have proper relationship. You should to take care of association and habtm migration, Have a look to below example, I have two model "User" and "Organization"

organization model

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

user model

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

Then need to create new OrganizationsUsers migration like below.

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

You can get working example from here.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top