Search code examples
ruby-on-railsrubysqliteinsertmany-to-many

#RubyOnRails Many to Many relationship not inserting into join table


I'm creating an app while learning how to code in Ruby. I'm making a simple league app where i can create new teams, players, leagues...

I have a team model and a league model and because a team can enter in more than one league and one league can have more than one team they are a many to many association. However, when i create / edit a team it doesnt insert anything into the join table, only changes the other attributes.

The models:

Team Model

class Team < ActiveRecord::Base
    validates_presence_of :name
    has_many :teams_join_leagues, :dependent => :destroy
    has_many :leagues, through: :teams_join_leagues
end

League Model

class League < ActiveRecord::Base
    validates_presence_of :name, :begindate, :enddate, :prizepool, :season_id

    validate :start_must_be_before_end_time

  has_many :teams_join_leagues, :dependent => :destroy
  has_many :teams, through: :teams_join_leagues

Join TeamLeague Model

class TeamsJoinLeague < ActiveRecord::Base
    belongs_to :team 
    belongs_to :league
end

TeamController param function:

def team_params
      params.require(:team).permit(:name, leagues: [:id])
    end

Create function:

def create
    @team = Team.new(team_params)

    respond_to do |format|
      if @team.save
        format.html { redirect_to @team, notice: 'Team was successfully     created.' }
    format.json { render :show, status: :created, location: @team }
  else
    format.html { render :new }
    format.json { render json: @team.errors, status: :unprocessable_entity }
    end
   end
 end

What i'm doing wrong? it never inserts anything on the join table leaving all the teams without leagues :/


Solution

  • Im assuming your teams_join_leagues table like this:

     create_table "teams_join_leagues", force: :cascade do |t|
        t.integer  "team_id"
        t.integer  "league_id"
        ....
      end
    

    so in your create team, it should look like this or similar

    def create
        @league = current_team.teams_join_leagues.build(league_id: params[:league_id])
        if @league.save
            ....
      end