【发布时间】:2019-01-17 08:46:21
【问题描述】:
我正在学习 Rails,希望能够在同一页面上使用相同的表单来添加元素(此处为“剂量”)或通过预填充表单来编辑现有元素(页面刷新后,我不需要动态执行)。
这是页面截图(views/cocktails/show.html.erb)
创建一个新的“剂量”可以正常工作,但是在尝试编辑 Rails 时会引发 “DosesController#edit 缺少此请求格式和变体的模板” 错误。
当我试图真正理解路由逻辑时,我这样做只是为了学习,即使这可能是一种不好的做法,而且我只想使用 Rails 来实现。
视图/剂量/_form.html.erb:
我将逻辑放入部分表单中以决定是创建还是更新@dose:
<% if @dose.new_record? %>
<%= simple_form_for [@cocktail, @dose] do |f| %>
<%= f.input :description %>
<%= f.association :ingredient %>
<%= f.button :submit %>
<% end %>
<% else %>
<%= simple_form_for @dose, url: url_for("doses#update") do |f| %>
<%= f.input :description %>
<%= f.association :ingredient %>
<%= f.button :submit %>
<% end %>
<% end %>
views/cocktails/show.html.erb:
我在这里调用“新的或编辑的”路径助手,将鸡尾酒 ID 和剂量 ID 传递给它,因为剂量属于一种鸡尾酒。
<% @cocktail.doses.each do |dose| %>
<li>
<h4><%= dose.description %> - <%= dose.ingredient.name %></h4>
<%= link_to "<i class=\"fas fa-pencil-alt\"></i>".html_safe, new_or_edit_dose_path(@cocktail.id, dose.id) %>
<%= link_to "<i class=\"far fa-trash-alt\"></i>".html_safe, dose_path(dose.id), method: :delete, data: {confirm: "Are you sure?"} %>
</li>
<% end %>
</ul>
<%= render "doses/form" %>
<%= link_to "Back", cocktails_path %>
</div>
routes.rb
此路径助手绑定到 GET 路由,与剂量控制器的编辑操作相关联。因此,我根本不会使用 dose#new 路线操作。
root to: "cocktails#index"
resources :cocktails, only: [:index, :show, :new, :create] do
resources :doses, only: [ :create]
end
resources :doses, only: [ :update, :destroy]
get "cocktails/:id/doses/:dose_id", to: "doses#edit", as: :new_or_edit_dose
doses_controller.rb
def edit
@cocktail = Cocktail.find(params[:id])
@dose = Dose.find(params[:dose_id])
end
def update
if @dose.update(set_params)
redirect_to cocktail_path(@dose.cocktail)
else
render(:edit)
end
end
def set_params
params.require(:dose).permit(:description, :ingredient_id)
end
我对问题的理解
我想问题是我正在使用鸡尾酒/:id/doses/:id 路线,但在鸡尾酒/:id/show 视图上显示表单。我尝试在doses#edit 末尾使用redirect_to 并将其传递给params,但没有成功。
谁能告诉我这是否可行,并提示我应该寻找什么?
【问题讨论】:
-
已找到编辑和更新路线,但如果视图目录中的 rails 找不到名为编辑或更新的模板,则会引发此错误。因此,如果您不想在一个模板中同时包含两个操作,则必须告诉 rails 在更新或编辑操作中要呈现什么。
标签: ruby-on-rails routes simple-form