【问题标题】:render 'new' page as partial将“新”页面呈现为部分
【发布时间】:2014-09-12 16:19:44
【问题描述】:

我正在构建这个应用程序,用户应该能够在同一页面中执行所有休息操作。所以下面的表格如下:

<div class="row">
  <div class="col-lg-3">Name</div>
  <div class="col-lg-4">Lastname</div>
  <div class="col-lg-3">Schedule</div>
  <div class="col-lg-1"> </div>
  <div class="col-lg-1"> </div>
</div>
<div id="table-body-clients">
  <% @clients.each do |client| %>
    <%= render :partial => 'client', :locals => { :client => client } %>
  <% end %>
</div>

我应该包含一个表单来添加一个新的客户端(相同的表单将加载和编辑选定的客户端。全部在远程)。

我能想到的最简单的方法是将“新”页面呈现为部分。但我似乎没有找到调用正确操作和/或正确加载本地人的方法。 这不起作用:

<%= render 'new', :controller => "clients", :action => "new", :locals => { :client => @client } %>
  • “new”实际上是一个名为“_new”的部分

无论如何,我希望能对此代码进行修复,并希望能深入了解解决问题的正确方法。 谢谢

【问题讨论】:

  • render partial: 'new', locals: { client: Client.new } 工作吗?
  • 没有@MrYoshiji。 “#:0x00000004eb5b28> 的未定义局部变量或方法‘client’”。也许是因为我使用设备和客户端扩展了用户?

标签: ruby-on-rails rest restful-architecture partials


【解决方案1】:

应该能够在同一页面中执行所有的休息动作

不必担心在同一页面上执行操作 - 确保您的视图结构保持在 Rails 的足智多谋的风格中,但在您想要的视图中调用它们(与使用局部视图非常相似)

正如你所展示的,你可以这样做:

<%= render "clients/new", locals: { client: @client } %>

在这里给你一个警告,你需要明白,因为你正在创建一个 client,你需要在你的控制器中构建资源:

#app/controllers/clients_controller.rb
class ClientsController < ApplicationController
   def index
     @clients = Client.all
     @client = Client.new
   end
end

--

正如你所说,你有一个 nested route(即 client 属于 company),你要确保你有以下设置:

#config/routes.rb
resources :companies do
   resources :clients #-> domain.com/companies/:company_id/clients
end

#app/controllers/clients_controller.rb
class ClientsController < ApplicationController
   def index
      @clients = Client.all

      @company = Company.find params[:company_id]
      @client = Client.new
   end
end

#app/views/clients/index.html.erb
<%= render "new", locals: {company: @company, client: @client} %>

#app/views/clients/new.html.erb
<%= form_for [company, client] do |f| %>
   ...
<% end %>

【讨论】:

    【解决方案2】:

    如下创建部分_form.html.erb

    <%= form_for client do |f| %>
    your form fields here
    <% end %>
    

    然后,从new.html.erbedit.html.erb,或者您需要表单的任何页面:

    <%= render "form", client: @client %>
    

    将@client 替换为您需要表单的实际client 对象。

    【讨论】:

    • 不,同样的问题:“未定义的局部变量或方法 `client' for #:0x00000004eb5b28>” on _form.html
    • 您使用的是什么版本的 ruby​​/rails?你能粘贴你实际的render 行(你尝试渲染部分的地方)吗?
    • 谢谢,已修复。我没有意识到客户属于公司,所以它需要两个参数: 'form', :locals => { :company => company, :client => company.clients.build } % >
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2018-10-20
    • 1970-01-01
    相关资源
    最近更新 更多