2013-01-16 56 views
0

在我的應用程序中,我有List對象和Problem對象,List由問題組成,問題可以屬於許多列表。我使用這兩個類HABTM和我創建自己的連接表像這樣:現在使用link_to將對象添加到HABTM關係表

class AddTableListsProblems < ActiveRecord::Migration 
    def up 
    create_table :lists_problems, :id => false do |t| 
    t.references :list 
    t.references :problem 
    t.timestamps 
end 
    end 

    def down 
    drop_table :lists_problems 
    end 
end 

,我的清單顯示視圖中,我打算顯示所有問題的列表,並提供一個「的link_to」將此問題添加到顯示的當前列表中,但我似乎無法弄清楚如何。我是RoR的新手,所以解決方案可能很簡單,雖然我似乎無法解決它。

這是我目前擁有的代碼。

<% @problems.each do |problem| %> 
     <%= render problem %> 
      | <%= link_to "Add to current list", <How do I access the List.problems method to add the problem and create a relation?> %> 
    <% end %> 

在此先感謝您的幫助。

回答

1

假設你有一個ListController。您將爲其添加add_problem操作。

def add_problem 
    list = List.find(params[:id]) 
    problem = Problem.find(params[:problem_id]) 

    list.problems << problem # This appends and saves the problem you selected 

    redirect_to some_route # change this to whatever route you like 
end 

而你需要爲此創建一條新路線。假設你正在使用足智多謀的路線,你可能有類似

resources :list do 
    member do 
    put "add-problem/:problem_id", action: :add_problem, as: :add_problem 
    end 
end 

,這將產生以下路由

add_problem_list PUT /list/:id/add-problem/:problem_id(.:format) list#add_problem 

在你看來,你會改變你的link_to

<% @problems.each do |problem| %> 
    <%= render problem %> 
     | <%= link_to "Add to current list", add_problem_list_path(list: @list, problem_id: problem.id), method: :put %> 
<% end %> 

注意這只是一個例子;你想在add_problem方法中進行授權/驗證/等等。

+0

這個做法很有用。 – nanomachine