Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如果不存在视频id,如何停止控制器查找视频id_Ruby On Rails - Fatal编程技术网

Ruby on rails 如果不存在视频id,如何停止控制器查找视频id

Ruby on rails 如果不存在视频id,如何停止控制器查找视频id,ruby-on-rails,Ruby On Rails,我的事件显示控制器中有以下代码: 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[:vi

我的事件显示控制器中有以下代码:

  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
这一行:

      @video = @event.videos.find(params[:video]) || @event.videos.first
如果视频已通过ID传递到参数,则应查找视频,例如通过以下链接:

event_path(video.event.name, video: video)
当视频被传递到参数中时,应用程序工作正常,正确的视频显示在正确的事件中

但是,如果未将视频ID传递到参数中,则会出现以下错误:

Couldn't find Video without an ID
我原以为| |操作符会跳过@event.videos.find(params[:video]部分,然后只选择与要显示的事件相关联的第一个视频,但很明显,这种情况不再发生,我认为在向视频添加友好的| id之后,这个问题就出现了,尽管我不能肯定

视频属于事件,一个事件有许多视频

有人能告诉我,当参数传递到@video时,如何让@video显示单击的视频,如果没有传递参数,则显示属于事件的第一个视频吗?

试试这个

if params[:video].nil?
    @video = @event.videos.first
else
   @video = @event.videos.find(params[:video])
end       

find
方法在没有具有此类id的记录时抛出异常(在您的情况下为nil)。请尝试此行:

@video = @event.videos.find_by_id(params[:video]) || @event.videos.first
如果params[:video]为空并且将返回
@event.videos.first
,则
find_by_id
方法将返回nil


另外,我认为您的代码中有一个bug:查看第二行(
Event.find by_name(params[:id])
)。如果它返回nil,则稍后
@Event.videos.present?
在nil上调用
videos
方法时抛出异常。

三元条件是您需要的

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

我认为你的代码中有一个bug,在我的回答中描述了它。非常感谢,成功了。我也会检查你发现的其他bug。