我的嵌套屬性有問題。我希望有人能夠訪問我的網站併爲活動添加歌曲。如果他們爲該事件提供派對代碼,他們只能添加這些歌曲。我想我的嵌套屬性設置正確,但我得到一個未經許可的參數錯誤。不允許的參數:songs_attributes
活動控制器:
class EventsController < ApplicationController
def new
@event = Event.new
@event.songs.build
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, :partycode])
end
end
application_controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
這裏是在歌曲new.html.erb文件視圖,其中包含的代碼將歌曲添加到該事件,注意用戶在添加歌曲時未登錄:
<br>
<br>
<div class ="container">
<div class="jumbotron">
<%= form_for Event.new do |f| %>
<h3>Enter a song:</h3>
<%= f.fields_for :songs, Song.new do |song_form| %>
<%= song_form.collection_select(:event_id, Event.all, :id, :name) %>
<%= song_form.text_field :artist, placeholder: "Artist" %>
<%= song_form.text_field :title, placeholder: "Title" %>
<%= song_form.text_field :genre, placeholder: "Genre" %>
<% end %>
<%= link_to_add_fields "Add Song", f, :songs %>
<%= f.text_field :partycode %>
<%= f.submit "Submit", class: "btn btn-primary" %>
<% end %>
</div>
</div>
link_to_add_fields方法d是在application_helper.rb文件:
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("songs_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
的songs_field部分被定義如下:
<fieldset>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
</fieldset>
的咖啡腳本,將字段:
$(document).on 'click', 'form .add_songs', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('event_id'), 'g')
$(this).before($(this).data('songs').replace(regexp, time))
event.preventDefault()
使人物從new.html.erb頁面將能夠從下拉菜單中選擇一個事件,然後按需添加更多的歌曲字段,然後爲他們挑選的某個事件輸入派對代碼。任何幫助,這將是太棒了!由於
編輯錯誤:
undefined method `events' for nil:NilClass
,似乎是一個錯誤的單一化/多元化。請發佈'event.rb'和'song.rb'。 – 31piy