屏蔽 Rails 中的链接

Masking Links in Rails

我目前正在尝试在我的 rails 应用程序中屏蔽一个 link,因为它 link 正在发送到不同的网站。我将在下面解释一个简单的场景:

目前悬停 link 我得到

http://www.testexampleoutsideurl.com/news/posts/1234

我正在努力让它显示

http://www.myapplication.com/offer/123

我在我的模型上使用 rails 脚手架设置和 friendly_id。我之前问过这个,但它给了我错误。请看下面的代码。

错误

PG::UndefinedColumn: ERROR: column offers.friendly_id does not exist LINE 1: SELECT "offers".* FROM "offers" WHERE "offers"."friendly_id... ^ : SELECT "offers".* FROM "offers" WHERE "offers"."friendly_id" IS NULL LIMIT 1

offers_controller.rb

# GET /offers/1.json
  def show
    link = Offer.find_by!(friendly_id: params[:slug])
    redirect_to link.url
  end

routes.rb

get "offers/:slug", to: "offers#show"

offer.rb

class Offer < ActiveRecord::Base
    belongs_to :category
  validates :category, presence: true

  extend FriendlyId
  friendly_id :title, use: :slugged

  mount_uploader :merchantImg, MerchantImgUploader
  mount_uploader :image, ImageUploader
end

如有任何帮助,我们将不胜感激!

更新

offers_controller.rb

  def show
    link = Offer.friendly.find(params[:slug])
    redirect_to link.url
  end

routes.rb

get "offers/:slug", to: "offers#show"

控制台错误

Couldn't find Offer without an ID

22:36:36 web.1    | [28829] 127.0.0.1 - - [17/Nov/2015:22:36:36 +0000] "GET /offers/blahihaidh HTTP/1.1" 404 118512 0.2532

错误说:

UndefinedColumn: ERROR: column offers.friendly_id does not exist

因此您的 table 没有名为 friendly_id 的列,因此查询崩溃。

您似乎在使用 friendly_id gem。 friendly_id README 有以下示例:

User.friendly.find(params[:id])

...但是您的代码如下所示:

link = Offer.find_by!(friendly_id: params[:slug])

您的代码失败是因为您正在尝试使用 ActiveRecord find_by! 方法,该方法将散列作为参数,其键应为列名,但您的 table 不是没有 friendly_id 列。相反,您应该按照 friendly_id README 指示并使用如下内容:

link = Offer.friendly.find(params[:slug])