2016-12-27 91 views
0

我一直在關注這個railscast:https://www.youtube.com/watch?v=t_FNKR7jahM學習如何實現嵌套屬性爲我的應用程序。當我在必要的某些領域執行他的代碼時,我總是在字段上得到相同的NoMethod錯誤。 enter image description hereNoMethod錯誤域嵌套屬性

在事件顯示頁面,您可以添加歌曲,我試圖添加一個添加字段鏈接,將添加另一組歌曲(藝術家,標題和流派的字段)。

這裏是我的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() 

對不起,對於我這個問題的答覆將很感激。讓我知道是否還有其他你需要從我(注意我使用軌道5)。乾杯:)

+0

「[...]上的字段相同NoMethod錯誤」?那個錯誤是? –

+0

它給我的錯誤是:未定義的方法'領域爲#<事件:0xc724098> – Aaron

回答

1

應該

f.fields_for :songs do |builder| 
+0

謝謝你,固定的字段錯誤。現在,我得到了一個field_type錯誤NoMethod不 – Aaron

+0

'Song'(這是在我的songs_field文件上面定義的)都稱爲'field_type'場? – Iceman

+0

不,它不會,我怎麼定義我的歌? – Aaron