1

假设您有一个简单的模型Project,您需要存储它的短 url 以供以后使用,什么时候计算它的最佳方法是?

我现在最好的解决方案是一个 after_create 钩子,但这会导致代码像

短网址 || Rails.application.routes.url_helpers.project_path(项目,主机:HOSTNAME)

从模型访问 url 感觉不对。

简而言之,您将计算 short_url 的代码放在哪里?

谢谢,

4

2 回答 2

0

您是否有理由不想保存确切的内容short_url?因此,当您需要项目对象的 url 时,您只需检查 short_url 是否存在。我相信你可以只添加一个装饰器来确定项目的 url。

#using Draper
class ProjectDecorator < Draper::Decorator
  def effective_url
    source.short_url.present? ? source.short_url : project_path(source)
    # or source.short_url || project_path(source) if short_url will not be an empty string
    # or source.short_url || source
  end
end
于 2013-03-30T10:48:31.070 回答
0

我会在控制器中添加这段代码。

class ProjectsController < ApplicationController
  def create
    @project = Project.new(params[:project])

    respond_to do |format|
      if @project.save
        @project.update_attribute(:short_url, project_url(@project))
        (..)
  end
end

It feels like this code belongs to the controller as it deals with http/url. Storing in the db sounds ok, but asking for the url is the controller's responsibility.

The line:

@project.update_attribute(:short_url, project_url(@project))

needs to be added below the call to .save (or .create), as only then the project_url helper can be called (the project object got its id already).

于 2013-03-30T15:37:11.660 回答