干栏表格 - 表格部分

时间:2014-07-12 15:28:23

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

我遇到了重复Rails表单代码的问题。当我把它们放在一个部分时,它们会抛出NoMethodError,我无法弄明白如何让它们变干。

admin / exam_centers / edit.html.erb =>

<%= simple_form_for(@exam_center, url: admin_exam_center_path(@exam_center)) do |f| %>
  <%= f.input :city_id, collection:City.all, label: 'Şehir Seçiniz', label_method: :name %>
  <%= f.input :address, label: 'Adres' %>
  <%= f.input :building, label: 'Bina' %>
  <%= f.button :submit, "Kaydet", :class => "btn btn-info" %>
<% end %>

注意:admin_exam_center_path(@exam_center)

admin / exam_centers / new.html.erb =&gt;

<%= simple_form_for(@exam_center, url: admin_exam_centers_path(@exam_center)) do |f| %>
  <%= f.input :city_id, collection:City.all, label: 'Şehir Seçiniz', label_method: :name %>
  <%= f.input :address, label: 'Adres' %>
  <%= f.input :building, label: 'Bina' %>
  <%= f.button :submit, "Kaydet", :class => "btn btn-info" %>
<% end %>

注意:admin_exam_centers_path(@exam_center)

他们的工作完美如此。但是当我将它们放在一个部分中时,如下所示,new.html.erb页面抛出“未定义的方法exam_centers_path”错误,而edit.html.erb页面则抛出“未定义的方法exam_center_path”错误。我如何制作这些表格DRYer?

_form.html.erb =&gt;

<%= simple_form_for(@exam_center) do |f| %>
  <%= f.input :city_id, collection:City.all, label: 'Şehir Seçiniz', label_method: :name %>
  <%= f.input :address, label: 'Adres' %>
  <%= f.input :building, label: 'Bina' %>
  <%= f.button :submit, "Kaydet", :class => "btn btn-info" %>
<% end %>

edit.html.erb =&gt;

<%= render 'admin/exam_centers/form' %>

new.html.erb =&gt;

<%= render 'admin/exam_centers/form' %>

顺便说一句,路线文件=&gt;

  namespace :admin do
   resources :exam_centers, except: :show
   resources :exam_languages, except: :show
  end

2 个答案:

答案 0 :(得分:2)

您似乎只需要使用polymorphic url构建器来指定路径的:admin段。尝试像这样指定表单助手:

<%= simple_form_for([:admin, @exam_center]) do |f| %>

这将允许Rails在生成其余路径之前在命名路由的admin_段上进行处理。

答案 1 :(得分:0)

你只将公共部分放在部分中,这样你就可以这样做:

<强> new.html.erb

<%= simple_form_for(@exam_center, url: admin_exam_centers_path(@exam_center)) do |f| %>
  <%= render partial: "form", locals: {:f => f} %>
<% end %>

<强> edit.html.erb

<%= simple_form_for(@exam_center, url: admin_exam_center_path(@exam_center)) do |f| %>
  <%= render partial: "form", locals: {f: "f"} %>
<% end %>

<强> _form.html.erb

<%= f.input :city_id, collection:City.all, label: 'Şehir Seçiniz', label_method: :name %>
<%= f.input :address, label: 'Adres' %>
<%= f.input :building, label: 'Bina' %>
<%= f.button :submit, "Kaydet", :class => "btn btn-info" %>