2015-10-19 68 views
0

我有一個編輯視圖。在這個視圖中,我得到了一個下拉菜單和一個呈現部分的表單。就像這樣:編輯特定對象

<ul class="dropdown-menu dropdown-user installations"> 
     <% @installations.each do |i| %> 
     <li><a href="#">Installation<%= i.installation_id%></a></li> 
     <% end %> 
</ul> 

<div class="ibox-content form-installations">       
     <%= render :partial => 'installations/test'%> 
     <%= render 'form_data' %> 
</div> 

編輯表單視圖:

<%= simple_form_for @installation, class: 'form-horizontal' do |f| %> 
     <%= f.error_notification %> 
     ... 
    <%end%> 

控制器:

def edit 
     @installations = current_user.installations 
     @installation = current_user.installations[0] 
    end 

所以在這一點上,我可以在下拉列表中所有設備看,但只能編輯第一「current_user.installations [0]」。所以我的目標是在下拉菜單中選擇安裝並編輯選定的安裝。我如何做到這一點?

+0

在您的'form'而不是'simple_form for @ installation' - >嘗試'simple_form for @ installations' – nik

回答

1

這樣做將是相關installation傳遞到下拉列表的最簡單方法:

#app/controllers/installations_controller.rb 
class InstallationsController < ApplicationController 
    def index 
     @installations = current_user.installations 
    end 
end 

#app/views/installations/index.html.erb 
<%= render @installations %> 

#app/views/installations/_installation.html.erb 
<%= simple_form_for installation do |f| %> 
    ... 
<% end %> 

我覺得有你的代碼結構的一些重大問題 - 這就是爲什麼你看到這些問題。


1.編輯

根據定義編輯member路線...

enter image description here

這意味着Rails的預計單個資源通過加載路線(因此你爲什麼得到url.com/:id/edit作爲路徑)。

原因很簡單 - Rails/Ruby是object orientated。這意味着每次你create/read/update/destroy (CRUD),你這樣做到對象

對象是通過使用@installation = Installation.new等等...這意味着調用,如果你想編輯您的安裝「所有」,你基本上需要使用收集途徑之一爲您Installations資源,發送任何場到update路徑:

#app/views/installations/_installation.html.erb 
<%= simple_form_for installation, method: :patch do |f| %> 
    ... 
<% end %> 

應該發送更新您的應用程序的installations#update路徑,使其正常工作。

-

2.局部模板

局部模板只是其可具有多種用途視圖;你應該只使用在其中使用「本地」變量。

有兩種方法來調用本地範圍變量分爲諧音:

  • 通過他們在locals: {}哈希
  • 將它們作爲在as: :__開關

在這兩種情況下,你」重新設置部分內部的「本地」變量以獲得僅在其之外可用的數據。

例如,你打電話:

<%= simple_form_for @installation 

... 部分。這很糟糕,因爲你依賴於@installation - 你最好使用installation並在你調用partial時填充它(正如我在上面的代碼中所做的那樣)。