如何在 rails 4 中使用 HABTM 将数据保存在数据库中

How to save data in database using HABTM in rails 4

我已经收录了

class User < ActiveRecord::Base  
  has_and_belongs_to_many :subjects
end  

class Subjects < ActiveRecord::Base  
  has_and_belongs_to_many :users
end  

我创建了一个 table 即 subjects_users 具有 subject_id 和 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 %>

它进入控制器方法:

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

请帮我解决这个问题。提前致谢

要为特定用户创建主题,您可以这样做:

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