0

I have the following code in my events show controller:

  def show
    @event = Event.find_by_name(params[:id])
    if request.path != event_path(@event)
      redirect_to @event, status: :moved_permanently
    end
    if @event.videos.present?
      @video = @event.videos.find(params[:video]) || @event.videos.first
      if :video_id.present? && current_user && @video.premium?
        @order = Order.new(user_id: current_user.id, video_id: @video.id, price: @video.price)    
      elsif :event_id.present? && current_user && @event.premium?
        @order = Order.new(user_id: current_user.id, event_id: @event.id, price: @event.price)    
      end
    end
    @user = User.new
  end

This line:

      @video = @event.videos.find(params[:video]) || @event.videos.first

Should find the video if it has been passed on ID into the params, such as by this link:

event_path(video.event.name, video: video)

When a video is passed into the params, the app works fine and the correct video is shown in the correct event.

However when a video ID isn't passed into the params, I get the following error:

Couldn't find Video without an ID

I thought that the || operator would skip past the @event.videos.find(params[:video] part and just pick the first videos associated with the event to display, but clearly this is no longer happening, and I think the problem has been introduced since adding friendly_id to videos, although I can't say for sure.

Videos belong to Events, and an Event has many Videos.

Can anyone help show me how I can have @video show the clicked video when the params are passed into it, and the first video belonging to the event if there are no params passed?

4

3 回答 3

1

find如果没有具有此类 id 的记录(在您的情况下为 nil),则方法将引发异常。试试这条线:

@video = @event.videos.find_by_id(params[:video]) || @event.videos.first

find_by_id如果 params[:video] 为空并且@event.videos.first将被返回,则该方法将返回 nil。

另外,我认为您的代码中存在错误:查看第二行(Event.find_by_name(params[:id]))。如果它返回 nil,那么稍后在 nil 上调用方法@event.videos.present?时会引发异常。videos

于 2013-11-01T13:31:15.357 回答
1

三元条件是你需要的..

@video = params[:video].present?  ? @event.videos.find(params[:video]) : @event.videos.first
于 2013-11-01T13:33:06.550 回答
0

试试这个

if params[:video].nil?
    @video = @event.videos.first
else
   @video = @event.videos.find(params[:video])
end       
于 2013-11-01T13:29:53.520 回答