简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM