提问人:Sergey Panov 提问时间:8/13/2023 最后编辑:Sergey Panov 更新时间:8/13/2023 访问量:21
从视图引用自定义资源路径
Reference custom resource path from the view
问:
我想从视图中调用自定义控制器方法“load”。我正在努力理解我应该如何在视图中调用要调用的路径。在我的routes.rb中,我有以下代码:
Rails.application.routes.draw do
resources :merchants_files, except: [:edit] do
member do
post 'load', :as => :load
end
end
在 merchants_files_controller.rb 控制器中,我有一个操作:
def load
CSV.foreach(@merchants_file.merchants_csv, headers: true, col_sep: ";") do |merchant|
Merchant.create!(merchant.to_hash)
end
respond_to do |format|
format.html { redirect_to merchants_files_url, notice: "Merchants loaded." }
end
end
在显示视图中,我尝试引用正确的路径来加载操作:
<p style="color: green"><%= notice %></p>
<%= render @merchants_file %>
<div>
<%= link_to "Back to merchants files", merchants_files_path %>
<%= button_to "Load the merchants file", merchants_file_load_path, method: :post %>
<%= button_to "Destroy this merchants file", @merchants_file, method: :delete %>
</div>
我尝试了除 merchants_file_load_path 之外的其他路径名,但我总是收到一个错误,即具有此名称的变量不存在。我应该如何从视图中引用自定义路径?我很难理解如何正确注册自定义控制器操作并使用视图中的自定义路径变量引用它。
我正在使用 Rails 7.0.6
答:
1赞
Sergey Panov
8/13/2023
#1
我自己也发现了。首先,我将路由代码简化为:
Rails.application.routes.draw do
resources :merchants_files, except: [:edit] do
member do
post :load
end
end
其次,这是我的工作观点:
<p style="color: green"><%= notice %></p>
<%= render @merchants_file %>
<div>
<%= link_to "Back to merchants files", merchants_files_path %>
<%= button_to "Load the merchants file", load_merchants_file_path, method: :post %>
<%= button_to "Destroy this merchants file", @merchants_file, method: :delete %>
</div>
我喜欢编写 rails 代码的感觉——这几乎就像用英语写文本一样
评论