2015-09-11 22 views
1

我已經包括如何將數據在數據庫中使用HABTM在軌道4,5

class User < ActiveRecord::Base 
    has_and_belongs_to_many :subjects 
end 

class Subjects < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

我已經創建了具有subject_id一個表即subjects_users和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 

請幫我解決這個問題。在此先感謝

回答

2

要爲特定的用戶創建對象,你可以做到這一點是:

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

不,我不希望創建主題我只想當學生將在主題cllick比它會去final_subject方法然後在表中用subject_user和user_id創建表中的行subject_user – user123

+0

檢查更新後的代碼 –