Varis Darasirikul
Varis Darasirikul

Reputation: 4177

How to create new record via has_many through by Rails?

I am currently struggling with a has_many :through association in my project.

This is my model

class Group < ActiveRecord::Base

  has_many :user_groups ,dependent: :destroy
  has_many :users , through: :user_groups

end

class User < ActiveRecord::Base

  has_many :user_groups ,dependent: :destroy
  has_many :groups , through: :user_groups

end

class UserGroup < ActiveRecord::Base

  belongs_to :user , inverse_of: :placements
  belongs_to :group , inverse_of: :placements

  validates :level , presence: true

end

So when i tried to create new group but it didn't work out. This is my controller

class GroupController < ApplicationController

    def create
        group = Group.new(group_params)
        group.users << User.find_by(id: current_user.id)

        if group.save
            render json: group, status: 201, location: [group]
        else
            render json: { errors: group.errors }, status: 422
        end
    end

    private

    def group_params
        params.require(:group).permit(:name, :shuttle_price, :court_price)
    end

end

But when i call create method i got this error.

Could not find the inverse association for group (:placements in Group)

On this line

group.users << User.find_by(id: 6)

So how can i fix this?

Thanks!

Upvotes: 0

Views: 641

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

Remove :inverse_of

class UserGroup < ActiveRecord::Base
  belongs_to :user
  belongs_to :group

  validates :level , presence: true
end

You don't need to add inverse_of there. read this when to use inverse_of

Upvotes: 1

Related Questions