我一直关注此railscast:https://www.youtube.com/watch?v=t_FNKR7jahM,了解如何在我的应用程序中实现嵌套属性。当我在必要的某些区域实现他的代码时,我总是在字段上得到相同的NoMethod错误。
在可以添加歌曲的活动节目页面上,我正在尝试添加“添加字段”。将添加另一组歌曲的链接(艺术家,标题和流派的字段)。
这是我的EventController:
class EventsController < ApplicationController
def new
@event = Event.new
@event.songs.build
end
def index
@songs = Song.all
end
def show
@event = Event.find(params[:id])
@songs = @event.songs.paginate(page: params[:page])
end
def create
@event = current_user.events.build(event_params)
if @event.save
flash[:success] = "Event Created!"
redirect_to user_path(@event.user)
else
render 'welcome#index'
end
end
def destroy
end
private
def event_params
params.require(:event).permit(:name, :partycode, song_attributes: [:artist, :title, :genre])
end
end
这是我的活动模型:
class Event < ApplicationRecord
belongs_to :user
has_many :songs, dependent: :destroy
accepts_nested_attributes_for :songs, allow_destroy: true
validates :name, presence: true
validates :partycode, presence: true, length: {minimum: 5}
end
以下是添加歌曲的节目页面:
<section class="song_form">
<%= render 'shared/song_form' %>
<%= form_for @event do |f| %>
<%= f.fields_for :fields do |builder| %>
<%= render 'events/songs_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Field", f, :fields %>
<% end %>
</section>
这是song_fields文件:
<fieldset>
<%= f.select :field_type, %w[text_field check_box] %>
<%= f.text_field :artist, placeholder: "Artist" %>
</fieldset>
这是ApplicationHelper文件:
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
最后,这是我的事件咖啡脚本文件;
$(document).on 'click', 'form .add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
对于冗长的帖子感到抱歉,我的问题的答案将非常感谢。如果您还需要我的其他信息,请告诉我(注意我使用的是rails 5)。干杯:)
答案 0 :(得分:1)
应该是
f.fields_for :songs do |builder|