如何将select_tag参数传递给button_to

时间:2015-07-19 12:30:31

标签: ruby-on-rails

我想将用户选择的:操作转移到下一页

index.html.erb

<td><%= select_tag :action, options_for_select(actions[account.type])%>
<%= button_to "execute", {:controller => "records", :action => "new", :type => :action, :account_name => account.name}, class: "btn btn-primary" %></td>

new.html.erb

<%= form_for @record do |f| %>
  <%= f.hidden_field :type, value: :type %>
  <%= f.hidden_field :account_name, value: params[:account_name] %>

  <div class="actions">
    <%= f.submit "Submit", class: "btn btn-primary" %>
  </div>
<% end %>

RecordController

class RecordsController < ApplicationController
  def index
    @records = Record.all
  end

  def new
    @record = current_user.records.build
  end

  def create
    @record = current_user.records.build(create_params)
    if @record.save
        flash[:success] = "Posted successfully"
        redirect_to('/root/tally_book')
    else
        redirect_to('/root/tally_book')
    end
end

def destroy
    @record = current_user.records.find_by(id: params[:id])
    if @record && @record.destroy
        flash[:success] = "Post deleted"
    else
        flash[:error] = "Cannot delete post"
    end
        redirect_to('/root/tally_book')
end

private

def create_params
    params.require(:record).permit(:account_name, :description, :usage, :type, :sum, :receipt)
end
end

帐号名称已成功发送

但是类型变为单词'type'而不是用户选择

如何转移:选择的用户类型?

2 个答案:

答案 0 :(得分:1)

试试这个

<%= form_tag(new_record_path(account_name: account.name), method: 'get' do %>
  <%= select_tag "action", options_for_select(actions[account.type]) %>
  <%= submit_tag "execute", class: "btn btn-primary" %>
<% end %>

答案 1 :(得分:1)

您是否希望将索引中的action选定选项作为新表单上的type进行转移?

index.html.erb

<td>
  <%= form_for(new_record_path(account_name: account.name), class: "btn btn-primary") do |f| %>
  # Not sure you need to specify method: :get, as it is already defined in your routes when you wrote `resources: :records`
  <%= select_tag :action, options_for_select(actions[account.type]) %>
  <%= submit_tag "execute", class: "btn btn-primary" %>
<% end %>

然后在你的new.html.erb

<%= form_for @record do |f| %>
  <%= f.hidden_field :type, value: params[:action] %>
  <%= f.hidden_field :account_name, value: params[:account_name] %>

  <div class="actions">
    <%= f.submit "Submit", class: "btn btn-primary" %>
  </div>
<% end %>

或者,您可以在控制器中实际执行此操作

def new
  @type = params[:action] ? params[:action] : DEFAULT_VALUE
end

and use `<%= f.hidden_field :type, value: @type %>`