【问题标题】:How to get a resource url in model如何在模型中获取资源 url
【发布时间】:2015-07-18 19:08:29
【问题描述】:

我有一个简单的姿势应用程序。如何从其模型中获取帖子网址并将其传递给 Bitly 缩短器? (将http://www.google.com替换为帖子网址)

大概是这样的

Rails.application.routes.url_helpers.posts_path(self...)

-

class TwitterWorker
  include Sidekiq::Worker

  def perform(title, url)
    tweet("#{title} #{url}")
  end
end

-

class Post < ActiveRecord::Base
  include Tweets
  extend FriendlyId

  after_create :post_to_twitter

.....

  private

  def post_to_twitter
    title = self.title[0..120]
    url = Bitly.client.shorten("http://www.google.com").short_url
    TwitterWorker.perform_async(title, url)
  end

end

-

我曾经在模型中有这段代码

 # tweet("#{title[0..120]} #{ Bitly.client.shorten('http://www.google.com').short_url}") 

向上 我最终做了以下事情。

由于我有几个模型可以发帖,所以我稍微重构了 post_to_tweeter 方法

工人

class TwitterWorker
  include Sidekiq::Worker
  include Tweets
  include Rails.application.routes.url_helpers

  def perform(message, slug)
    url = Bitly.client.shorten(post_url(slug, host: ActionMailer::Base.default_url_options[:host])).short_url
    tweet("#{message} #{url}")
  end
end

型号

after_create :post_to_twitter

def post_to_twitter
  message = "#{self.title[0..120]}"
  TwitterWorker.perform_async(message, self.slug)
end

【问题讨论】:

  • 模型不应该知道任何关于 url 的事情。将您的方法移到其他地方,例如帮助器。

标签: ruby-on-rails ruby


【解决方案1】:

您可以包含网址 模型中的助手(尽管它 通常不是最好的方法 处理事情)

class MyClass < ActiveRecord::Base
  include Rails.application.routes.   url_helpers
end

【讨论】:

    【解决方案2】:

    如果您在 URL 中使用模型 ID,则可以使用以下代码。不过,我喜欢使用 obfuscate_id 和/或 friendly_id gem 来防止用户知道数据库中有多少条记录。

    型号:

    class Post < ActiveRecord::Base
    
    ...
    
    private
    
      def post_to_twitter
        title = self.title[0..120]
        TwitterWorker.perform_async(title, self.id)
      end
    end
    

    推特工作者:

    class TwitterWorker
      include Sidekiq::Worker
    
      def perform(title, post_id)
        tweet("#{title} Bitly.client.shorten(post_url(#{post_id})).short_url) 
      end
    end
    

    如果帖子 ID 为 123,这会将 url 设置为 http://localhost.com/post/123

    要设置您的网站在暂存和生产环境中的内容,请阅读以下内容 - How does rails 4 generate _url and _path helpers

    附:您还可以使用 post_url 技巧在电子邮件中包含绝对 URL。

    【讨论】:

    • 如果我只使用 post_url 它是行不通的。我可以通过使用 Rails.application.routes.url_helpers.post_path(slug) 来获取路径。帖子/post_name。 Post_url 给 Missing host 链接到!请提供 :host 参数,设置 default_url_options[:host],或设置 :only_path 为 true
    • 刚刚记得你需要在模型中包含它,但对于控制器、视图和邮件程序你不需要:api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2018-03-16
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多