2017-02-10 48 views
1

在我的ruby on rails網站中,我列出了希望允許用戶向願望清單添加列表的列表。我的房源模型has_many心願和我的心願單模型has_and_belongs_to_many房源。Ruby on Rails - 獲取所選單選按鈕的模型ID

add_listing_to_a_wishlist.html.erb文件看起來像:

<table> 
    <tbody> 
    <% @wishlists.each do |wishlist| %> 
    <tr> 
     <%= radio_button_tag("wishlist[id]", wishlist.id) %> 
     <%= wishlist.name %>&nbsp; 
    </tr> 
    <% end %> 
    </tbody> 
</table> 
<%= link_to "Add listing to selected wishlist", wishlist_path %> 

這成功地檢索和顯示了一個可點擊的單選按鈕,每一個心願。我想通過選定的心願(選擇單選按鈕)中的鏈接:

<%= link_to "Add listing to selected wishlist", wishlist_path %> 

在我的列表控制器,我有一個add_listing_to_wishlist功能,我打算使用各自上市的ID和願望清單添加列表。它看起來像:

def add_listing_to_wishlist 
    @listing = Listing.find(params[:id]) 
    @wishlists = Wishlist.find(params[:id]) 
    # [Logic for saving listing to wishlist here] 
    end 

如何有效地將選定的願望清單從UI傳遞到此功能?

我是Ruby on Rails和前端開發的新手,所以我可能缺少一個簡單的概念;任何指針都非常感謝。

回答

1

我不知道,也許我的方式是不行的,但它的工作原理爲了我。只需將表單添加到您的代碼。

<%= form_tag wishlist_path, method: :patch, remote: true do %> 
<table> 
    <tbody> 
    <% @wishlists.each do |wishlist| %> 
    <tr> 
     <%= radio_button_tag("wishlist[id]", wishlist.id) %> 
     <%= wishlist.name %>&nbsp; 
    </tr> 
    <% end %> 
    </tbody> 
</table> 
<%= submit_tag 'Add to wishlist', class: 'btn btn-primary' %> 
<% end %> 
1

你需要保持的名字,只要你想帕拉姆並更改值

<table> 
    <tbody> 
    <% @wishlists.each do |wishlist| %> 
    <tr> 
     <%= radio_button_tag("wishlist", wishlist.id) %> 
     <%= wishlist.name %>&nbsp; 
    </tr> 
    <% end %> 
    </tbody> 
</table> 

並在控制器

def add_listing_to_wishlist 
    @listing = Listing.find(params[:id]) 
    @wishlists = Wishlist.find(params[:wishlist]) 
    # [Logic for saving listing to wishlist here] 
    end 
相關問題