Sushant Bajracharya
Sushant Bajracharya

Reputation: 400

Inserting data into foreign key column

I have a user and group table. In user table I have id,name . In group table I have id group_name, created_by , user_id. Here a user can belong to more than one group but not the same group twice. A group can have many users but not the same user twice.

Here is my code.

group.rb

module Client
  class Group < ActiveRecord::Base
    has_many :users
  end
end

user.rb

class User < ActiveRecord::Base
  belongs_to :client_groups
end

Now when a user creates a new group, he should be automatically be persisted into the user_id and created_by field. So as per the guides , I tried to follow the same with my code like this

@user.Client::Group.new(client_group_params)

but it gave me an err.

So I tried another way,

def create
      @client_group = Client::Group.new(client_group_params)
      client_group_params[:created_by] = current_user.id
      client_group_params[:users_id] = current_user.id
      @client_group.save
      respond_with(@client_group)
    end

def client_group_params
      params.require(:client_group).permit(:group_name)
    end

It saved the group_name into the db but it did not save the created_by and the users_id field. Any idea?

I have made the user_id field foreign key.

Upvotes: 0

Views: 503

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

First, you need to change the assoication declaration as below:

class User < ActiveRecord::Base
  belongs_to :client_group,
    class_name: 'Client::Group',
    foreign_key: :group_id
end

As per the association you have, the User model should have the column called group_id. Add it through migration. I am not seeing the point of adding the user_id to the Group model.

Then change the create action as :

def create
  @client_group = current_user.build_client_group(
    client_group_params.merge(created_by: current_user.id)
   )
  @client_group.save
  respond_with(@client_group)
end

Upvotes: 2

Related Questions