【发布时间】:2016-12-27 20:43:54
【问题描述】:
我一直在关注这个 railscast:https://www.youtube.com/watch?v=t_FNKR7jahM,以了解如何在我的应用程序中实现嵌套属性。当我在某些必要的区域实现他的代码时,我总是在字段上得到相同的 NoMethod 错误。
在您可以添加歌曲的活动显示页面上,我正在尝试添加一个“添加字段”链接,该链接将添加另一组歌曲(艺术家、标题和流派的字段)。
这是我的事件控制器:
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)。干杯:)
【问题讨论】:
-
“[...] 字段上出现相同的 NoMethod 错误”?那个错误是?
-
它给我的错误是:#<0xc724098>0xc724098>
标签: javascript ruby-on-rails nested-attributes