user123
user123

Reputation: 163

How to save data in database using HABTM in rails 4

I have included

class User < ActiveRecord::Base  
  has_and_belongs_to_many :subjects
end  

class Subjects < ActiveRecord::Base  
  has_and_belongs_to_many :users
end  

I have created one table i.e subjects_users having subject_id and user_id

<% Subject.all.each do |subject| %>
    <tr>
      <td><%= subject.name %></td>
      <td><%= link_to 'Select Subject', final_subject_subject_path(subject)  %></td>
    </tr>
  <% end %>

It goes in controller method:

def final_subject
    # now please guide me what I have to write in this so that when select subject is clicked than it will both current_user.id and subject.id in associated table
  end

Please help me out in solving this. Thanks in advance

Upvotes: 1

Views: 307

Answers (1)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

To create subjects for a particular user, you can do it as:

def final_subject
    @subject = Subject.find(params[:id)
    current_user.subjects << @subject
end

Upvotes: 2

Related Questions