2015-10-19 66 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时填充它(正如我在上面的代码中所做的那样)。