如何从模板中的控制器传输值?

时间:2015-07-01 13:17:58

标签: ruby-on-rails ruby-on-rails-4

请帮助解决问题。

页面显示用户列表和排序表单:

....
...
<%= form_tag(admin_users_path, method: 'get') do %>
  <%= select_tag "fld_order", options_for_select([ "Ascending", "Descending" ], quantity) %>
  <%= select_tag "fld_quantity", options_for_select([ "5", "10", "50", "100" ], order) %>
  <%= submit_tag "Sort", class: "btn_submit" %>
<% end %>

控制器:

      def index
        quantity = params[:fld_quantity] || 10
        order = params[:fld_order] || 'Ascending'

        if params[:fld_order] == 'Descending'
          @users = ::User.paginate(page: params[:page], :per_page => quantity).order(name: :DESC)
        else
          @users = ::User.paginate(page: params[:page], :per_page => quantity).order(name: :ASC)
        end

render :index, :locals => {:quantity => quantity, :order => order}
      end

排序工作。但我需要以实际形式匹配值。问题是他们总是违约。

请帮助将quantity, order从控制器转移到模板

1 个答案:

答案 0 :(得分:1)

orderquantity变量需要是实例变量,并删除render - 不需要它:

  def index
    @quantity = params[:fld_quantity] || 10
    @order = params[:fld_order] || 'Ascending'

    if params[:fld_order] == 'Descending'
      @users = ::User.paginate(page: params[:page], :per_page => quantity).order(name: :DESC)
    else
      @users = ::User.paginate(page: params[:page], :per_page => quantity).order(name: :ASC)
    end
  end

我还认为get是默认

<%= form_tag(admin_users_path) do %>
  <%= select_tag "fld_order", options_for_select([ "Ascending", "Descending" ], @quantity) %>
  <%= select_tag "fld_quantity", options_for_select([ "5", "10", "50", "100" ], @order) %>
  <%= submit_tag "Sort", class: "btn_submit" %>
<% end %>

同时检查代码中的拼写错误或拼写错误: - )