我正在使用嵌套属性,直到提交信息并收到此错误之前,一切似乎都还不错。它说它在我的EventsController文件中:
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: [:event_id, :artist, :title, :genre, :partycode])
end
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方法在我的ApplicationHelper.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
在session_helper.rb文件中定义了current_user:
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
def createEvent(event)
session[:event_id] = event.id
end
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
def log_out
session.delete(:user_id)
@current_user = nil
end
end
最后,这是我的songs_fields文件,该文件仅在用户单击显示“添加歌曲”的链接时才生成字段
<fieldset>
<%= f.text_field :artist, placeholder: "Artist" %>
<%= f.text_field :title, placeholder: "Title" %>
<%= f.text_field :genre, placeholder: "Genre" %>
</fieldset>
我觉得这是我使应用程序中的所有功能正常工作之前的最后一部分!因此,对此的帮助将是巨大的:D
您回答了自己的问题...如果您尚未登录,则current_user将为nil,因此会出现此错误。
选项1(丑):改变你的逻辑,所以current_user.events如果没有得到所谓的CURRENT_USER是零,只是直奔渲染
选项2(更好):在运行操作之前,使用before_action语句强制设置current_user。取决于您用来进行身份验证的内容,但是使用Devise时,它看起来像这样:
class EventsController < ApplicationController
before_action :authenticate_user!
我想也许是:
class EventsController < ApplicationController
before_action :log_in(user)
可能会为您做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句