为控制器而不是实例设置了Self



我正在创建一个简单的url shorterer应用程序。在模型中,我有一个方法,它创建要使用的short_url,而不是原始url。

class ShortenersController < ApplicationController
before_action :find_shortener, only: [:info, :show] 
before_action :generate_unigue_shorty, only: [:create]
def new
@shortener = Shortener.new
end
def create
@shortener = Shortener.new
@shortener.main_url = params[:main_url]
if @shortener.save
redirect_to info_path(@shortener.short_url)
else
flash[:notice] = "Someting went wrong"
render 'new'
end
end
private
def shortener_params
params.require(:shortener).permit(:main_url, :short_url)
end
def find_shortener
@shortener = Shortener.find_by_short_url(params[:short_url])
end
end

型号:

class Shortener < ApplicationRecord
before_create :generate_unique_shorty
def generate_unique_shorty
shorty = SecureRandom.hex(4)
if  Shortener.all.any? {|a| a.short_url == shorty}
self.generate_unique_shorty
else
self.short_url = shorty
end
end
end

我得到的错误:#ShortenersController:0x00007fbfbc735db0的未定义方法"generate_unigue_shorty">看起来此方法中的self对象被设置为Controller对象,它应该是Shortener类(@Shortener(的实例

此处键入:generate_unigue_shortyg=>q

此外,在您的控制器中没有名为generate_unique_shorty的方法。控制器中的before_action确实在控制器中查找方法,而不是在模型中。

话虽如此,由于您的模型中已经有一个before_create回调,它确实生成了一个uniq shorty,因此无需在控制器中复制此行为。

TL;DR:从控制器中删除before_action :generate_unigue_shorty, only: [:create]

在你的代码中有更多的东西需要重新思考,我没有涉及,因为这将是偏离主题的

相关内容

最新更新