【发布时间】:2020-04-05 19:01:27
【问题描述】:
我正在开发这个 ruby on rails 项目,用户可以在其中向食谱添加成分。现在在新的食谱页面上,用户只能添加一种成分,我希望他们能够在创建或编辑食谱时添加许多成分。我试过了,据我所知,一切似乎都井然有序,但“添加成分”链接只是重新加载了整个页面。
_form.html.erb
<link rel="stylesheet" type="text/css" href="app/assets/stylesheets/form.css">
<div id = "form">
<%= form_for(@recipe) do |form| %>
<% if @recipe.errors.any? %>
<div id = "error_explanation">
<h2>
<%= pluralize(@recipe.errors.count, "error") %>
prohibited this recipe from being saved:
</h2>
<ul>
<%@recipe.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :author %><br>
<%= form.text_field :author %>
</p>
<p>
<%= form.label :note %><br>
<%= form.text_area :note %>
</p>
<h2 id = "add">Add an Ingredient: </h2>
<%= form.fields_for :ingredients do |builder| %>
<%= render 'ingredient_fields', form: builder %>
<% end %>
<%= link_to_add_fields "Add Ingredient", form, :ingredients %>
<p>
<%= form.submit %>
</p>
<% end %>
</div>
_ingredient_field.html.erb
<link rel="stylesheet" type="text/css" href="app/assets/stylesheets/ingredient_form.css">
<p class = "input_field">
<%= form.label :name, "name" %><br>
<%= form.text_field :name %>
</p>
<p class = "input_field">
<%= form.label :amount, "amount" %><br>
<%= form.number_field :amount %>
</p>
<p class = "input_field">
<%= form.label :uom, "UOM" %><br>
<%= form.text_field :uom %>
</p>
</br>
食谱.rb
class Recipe < ApplicationRecord
attr_accessor :name, :ingredients_attributes
has_many :ingredients, :dependent => :delete_all
accepts_nested_attributes_for :ingredients, reject_if: :all_blank
validates :title, presence: true, length: {minimum: 4}
validates :author, presence: true
end
application_helper.erb
module ApplicationHelper
def link_to_add_fields(name, form, association)
new_object = form.object.send(association).klass.new
id = new_object.object_id
fields = form.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + '_fields', form: builder)
end
link_to(name, '#', class: 'add_fields', data:
{ id: id, fields: fields.gsub("\n", '') })
end
end
recipe.js.coffee - 这是我最怀疑的。我不太了解jQuery 和coffeescript。我在 javascript/packs 中有这个文件,并且在 application.html.erb 中使用了 require("packs/recipes")。
jQuery ->
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
谢谢
【问题讨论】:
-
你可能想看看这个宝石:github.com/nathanvda/cocoon.
标签: jquery ruby-on-rails ruby-on-rails-6