【问题标题】:How to pass a value from a view to another view to populate another form in rails 3如何将值从视图传递到另一个视图以填充 Rails 3 中的另一个表单
【发布时间】:2012-05-08 23:43:28
【问题描述】:

如何将值从一个视图传递到另一个视图以填充 rails 3 中的另一个表单?

我是 Rails 新手,对如何实现这一点有点困惑,这是我的场景:

我生成了一个客户和一个销售脚手架,然后在客户索引视图中放置了一个搜索文本字段,用于搜索客户并将其呈现在其下方。每个客户都有一个名为“销售”的按钮,点击后它会将您重定向到 new_sales_path 并自动用客户的值填写表单的某些字段,例如:姓名、地址、id、电话号码等...

所以我想做的是: 我想在单击“销售”按钮时传递客户的信息,然后填写 new_sales 表单。

所以我在索引客户端视图中有这段代码:

<%= form_tag clientes_path, :method => 'get', :id => "clientes_search", :class => "form-search" do %>
<p>
<%= text_field_tag :search, params[:search], :class => "input-medium search-query" %>

<%= submit_tag "Search", :name => nil, :class => "btn" %>

<% @clients.each do |client| %>
<tr>
<td><%= client.id %></td>
<td><%= client.email %></td>
...
...
<%= link_to t('.edit', :default => t("helpers.links.edit")),
                  edit_client_path(client), :class => 'btn btn-mini' %>
<%= link_to "Sale", new_sale_path, :action => 'sale_button', :id => 'sale_button', :class => 'btn btn-mini' %>
<% end %>
</tr>
<% end %>

在我的应用程序助手中,我有:

def sale_button
@sale_button = client
end

在我的客户和销售主管中,我有这样一句话:

helper_method :sale_button

在我的新销售视图中,我有

<div id='sales'>
<%= simple_form_for @sale, :html => { :class => 'form-horizontal' } do |f| %> 
<%= f.input :client, :label => "Client ID", :required => true, :as => :string, :input_html => { :value => @sale_button.id } %>
...
... 
<% end %>

我不知道我的做法是否正确,或者我是否缺少某些东西,欢迎提供任何帮助或意见。

我正在使用 Rails 3.2 顺便说一句


销售总监

class SalesController < ApplicationController
before_filter :authenticate_user!
helper_method :sort_column, :sort_direction
helper_method :boton_venta


  # GET /sales
  # GET /sales.json
  def index
    @sales = Sale.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 10, :page => params[:page])
    @lista_porcentajes = Porcentaje.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @sales }
      format.js
    end
  end

  # GET /sales/1
  # GET /sales/1.json
  def show
    @sale = Sale.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @sale }
    end
  end

  # GET /sales/new
  # GET /sales/new.json
  def new
    @sale = Sale.new
    @client = Client.find(params[:client_id])
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @sale }
      format.json { render json: @client }
    end
  end

  # GET /sales/1/edit
  def edit
    @sale = Sale.find(params[:id])
  end

  # POST /sales
  # POST /sales.json
  def create
    @sale = Sale.new(params[:sale])

    respond_to do |format|
      if @sale.save
        format.html { redirect_to @sale, notice: 'Sale was successfully created.' }
        format.json { render json: @sale, status: :created, location: @sale }
      else
      format.html { render action: "new" }
        format.json { render json: @sale.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /sales/1
  # PUT /sales/1.json
  def update
    @sale = Sale.find(params[:id])

    respond_to do |format|
      if @sale.update_attributes(params[:sale])
        format.html { redirect_to @sale, notice: 'Sale was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @sale.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /sales/1
  # DELETE /sales/1.json
  def destroy
    @sale = Sale.find(params[:id])
    @sale.destroy

    respond_to do |format|
      format.html { redirect_to sales_url }
      format.json { head :no_content }
    end
  end

  private

  def sort_column
    Sale.column_names.include?(params[:sort]) ? params[:sort] : "id"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end

routes.rb

Puntodeventa::Application.routes.draw do

  resources :empresas

  resources :cliente_grupo_empresas

  devise_for :users, :admin_empresas, :empresa_users, :cliente_users, :admins

  resources :relacion_porcentaje_grupoempresas

  resources :relacion_grupo_empresas

  resources :porcentajes

  resources :categoria_empresas

  resources :grupo_empresas

  resources :sales

  resources :cliente_empresas

  resources :clients

  get "home/index"

  resources :productos

  root :to => "home#index"

搜索路线

sales GET    /sales(.:format)                                      sales#index
                                  POST   /sales(.:format)                                      sales#create
                         new_sale GET    /sales/new(.:format)                                  sales#new
                        edit_sale GET    /sales/:id/edit(.:format)                             sales#edit
                             sale GET    /sales/:id(.:format)                                  sales#show
                                  PUT    /sales/:id(.:format)                                  sales#update
                                  DELETE /sales/:id(.:format)                                  sales#destroy

sales new.html.erb

<%- model_class = @sale.class -%>
<h1><%=t '.title', :default => t('helpers.titles.new', :model =>     model_class.model_name.human,
                               :default => "New #{model_class.model_name.human}") %>      </h1>
<%= render :partial => 'form' %>

在 sales new.html.erb 中呈现的表单

    <div id='sales'>

<%= simple_form_for @sale, :html => { :class => 'form-horizontal' } do |f| %>

  <%= f.input :client, :label => "Serial del cliente", :required => true, :as => :text, :input_html => { :value => ' ' } %>
  <%= f.association :client, :label_method => :nombre, :label_value => :id, :required => true, :as => :string %>
  <%= f.association :porcentaje, :label_method => :porcentaje, :value_method => :porcentaje, :required => true %>
  <%= f.input :monto_venta, :required => true, :as => :string %>
  <% if current_user.try(:admin?) %>
  <%= f.association :empresa, :label_method => :nombre, :value_method => :id, :required => true %>
  <% else %>
  <% f.association :empresa, :disabled => true, :input_html => { :value => current_user.empresa_id } %>
  <% end %>
  <div class="form-actions">
    <%= f.button :submit, :class => 'btn-primary' %>
    <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                sales_path, :class => 'btn' %>
  </div>
<% end %>

</div>

具有您建议的修改的新销售视图。

<table class="table table-striped">
  <thead>
    <tr>
      <th><%= sortable "id", "Id" %></th>
      <th><%= sortable "name", "Name" %></th>
      <th><%= sortable "grupo_empresa", "Grupo" %></th>
      <th><%= sortable "telefono", "Telefono" %></th>
      <th><%= sortable "celular", "Celular" %></th>
      <th><%= sortable "email", "Email" %></th>
      <th><%= sortable "serial_cliente", "Serial del cliente" %></th>
      <th><%= sortable "puntos_cliente", "Puntos del cliente" %></th>
        <th><%= sortable "created_at", "Creado el" %></th>
        <th><%=t '.actions', :default => t("helpers.actions") %></th>
    </tr>
  </thead>
  <tbody>
    <% @clients.each do |client| %>
      <tr>
        <td><%= client.id %></td>
        <td><%= link_to client.nombre, client_path(client) %></td>
        <td><%= client.grupo_empresa.nombre %></td>
        <td><%= client.telefono %></td>
        <td><%= client.celular %></td>
        <td><%= client.email %></td>
        <td><%= client.serial_client %></td>
          <td><%=l client.created_at %></td>
        <td>
          <%= link_to t('.edit', :default => t("helpers.links.edit")),
                      edit_client_path(client), :class => 'btn btn-mini' %>
        <%= link_to "Sale", new_sale_path, :client_id => client.id , :id => 'boton_venta', :class => 'btn btn-mini' %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    仔细听,

    以下链接“Sale”应该在您的应用程序中。

    <%= link_to "Sale", new_sale_path, :client_id => client.id , :class => 'btn btn-mini' %>
    

    如果用户单击该链接,link_to 方法会检查路径并且您已将其称为“new_sale_path”

    来自您的“rake routes”,

    new_sale GET    /sales/new(.:format)                                  sales#new
    

    很明显 new_sale_path 指的是 sales#new(sales controller, new action)

    如果你添加下划线路径,rails 会处理这个问题。例如,edit_sale_path 将执行销售控制器,编辑操作/方法。

    在这一步之后,由于sales控制器中的新动作被执行,rails会在app/views/sales中寻找一个“new.html.erb”文件。

    如果存在,该 html.erb 文件将在您的浏览器中显示/呈现。

    你应该明白上面的工作原理。

    现在,让我们具体一点。

    当单击该销售链接时,应用程序会到达 sales#new 操作,其中 :client_id 作为 params 哈希中的参数。

    您可以按如下方式访问该参数哈希,

    @client = Client.find(params[:client_id])
    

    你已经做到了。上述语句,将传递的 :client_id 作为输入,并使用 Client 模型和 find 方法从数据库中找到正确的客户端。

    现在,实例变量已设置为 Clients 表中与 :client_id 匹配的记录。

    实例变量是@client。

    现在,在您看来,您可以按如下方式使用实例变量@client,您还没有这样做,或者我没有看到。 app/views/sales/_form.html.erb 中有什么?

    请也发布。

    <%- model_class = @sale.class -%>
    <h1><%=t '.title', :default => t('helpers.titles.new', :model =>     model_class.model_name.human,
                                   :default => "New #{model_class.model_name.human}") %>      </h1>
    <%= render :partial => 'form' %>
    

    如果你使用如下的 form_for,

    <% form_for @client do |client| %>
    
    <% text_field_tag client.name %>
    -
    -
    -
    
    <% end %>
    

    会有一个 text_field 预填充客户的姓名。

    如果你有什么不明白的地方,请告诉我。

    如果你了解的东西很少,但想不通的东西很少,请告诉我。

    如果你明白一切,请告诉我。

    谢谢。

    【讨论】:

    • 哦,好的,我明白你在说什么,但也许我没有正确解释自己,让我试试。我有 2 张桌子,客户和销售,我提到的销售按钮在客户索引视图“app/views/clients/index.html.erb”中,它显示了所有客户,每个客户都有一个销售按钮。当按下此按钮时,它会将用户重定向到新的销售视图“app/views/sales/new.html.erb”,效果很好,它会将我重定向到它并显示页面。我不能做的是将特定客户的 id 传递给新的销售视图,我不知道该怎么做,因为...
    • 它们位于不同的控制器中,“app/controllers/clients_controller.erb”和“app/controllers/sales_controller.erb”。我将在销售按钮出现的位置粘贴客户索引视图,以便您知道我在说什么。
    • 听着,试试这个,你在这个链接中将客户端 ID 作为参数传递。 "sales", :action => "new", :client_id => client.id} , {:class=> 'btn btn-mini'} %>。现在将其用作您的销售链接。单击它并复制并粘贴您在浏览器地址栏中获得的 URL,然后单击它。
    • 实际上在我的问题中,第一段代码是我的客户索引视图,因此您可以看到重定向到销售新路径的销售按钮。
    • 好的,将链接替换为, "sales", :action => "new", :client_id => client.id} , {: class=> 'btn btn-mini'} %>。现在将其用作您的销售链接。单击它并复制并粘贴您在浏览器地址栏中获得的 URL,然后单击它。
    【解决方案2】:

    将 client_id 作为参数传递给此链接,

     <%= link_to "Sale", new_sale_path, :client_id => client.id , :class => 'btn btn-mini' %>
    

    确保 new_sale_path 击中销售控制器,新操作。

    在新操作中,以 params[:client_id] 的形式访问 client_id 并获取当前客户端记录并呈现如下表单,

    SalesController
    
    def new
     @client = Client.find(params[:client_id])
     -
     -
     -
     render 'new'
    end
    

    在你看来,new.html.erb,你必须写一个form_for @client as,

    <% form_for @client do |client| %>
    
    <% text_field_tag client.name %>
    -
    -
    -
    
    <% end %>
    

    现在,我不确定我的语法。试着理解我在这里做什么。

    谢谢。

    【讨论】:

    • 我按照你的建议做了,当它把我重定向到 new_sales_path 时,我收到以下错误:找不到没有 ID 的客户
    • 这是错误,它还说:app/controllers/sales_controller.rb:34:in `new'
    • 所以我认为发生的事情是变量 client_id 为 nil,所以这就是销售控制器中的“新”操作抱怨的原因。如果您需要完整的跟踪信息,请点击此处:pastebin.com/48sLafTJ
    • 请复制粘贴您的 app/controllers/sales_controller.rb 和 app/views/sales/new.html.erb 代码以及您的 routes.rb!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    相关资源
    最近更新 更多