从表单提交将视图中的变量传递给控制器

时间:2015-03-16 22:37:28

标签: ruby-on-rails variables model-view-controller form-for

我正在尝试访问通过提交表单发送的变量。但是,一旦表单提交,它似乎不存在。

在线看到隐藏字段:2

<%= form_for @import, html: { multipart: true } do |f| %>
  <%= f.hidden_field :tree_id, :value => @tree.id %>
  <%= f.label :new_branch_data %>
  <div class="help-text">Locate a file for import. (.xls, .xlsx file type)</div>
  <%= f.file_field :attachment %>
  <%= f.submit "Import", class: "btn btn-primary" %>
<% end %>

点击提交我的控制器中调用的动作后:

def index
 @tree = Tree.find(params[:tree_id]) 
 ...
 ...
end

挂断@tree = Tree.find(params[:tree_id])并返回

&#34; ActiveRecord的:: RecordNotFound&#34; at /进口 无法找到没有ID的树

如何更正此问题,以便将表单中引用的@tree变量传递给控制器​​?

2 个答案:

答案 0 :(得分:1)

你可以检查你得到的参数但我猜你在params [:import]上有tree_id所以......

def index
  @tree = Tree.find(params[:import][:tree_id]) 
  ...
  ...
end

答案 1 :(得分:0)

我意识到我没有直接调用索引操作。

在查看我的控制器时,我实际上正在调用create action,后来重定向到索引。

def create
   @import = Import.new(import_params)

   if @import.save
     redirect_to imports_path, notice: "Data imported successfully."
   else
     render "new"
   end
end

我更改了重定向以传递参数,

redirect_to imports_path(tree_id: params[:import][:tree_id]), notice: "Data imported successfully."

然后通过添加

在索引视图中访问传递的param

@tree = Tree.find(params[:tree_id])

到索引操作的顶部。

相关问题