简体   繁体   中英

How to get root_url into interpolation inside rails model concerns

I am trying to add root_url to "#{url}#{uuid}", but what I have results to another path ie http://localhost:3000/links/15/yeyb7ebdbee instead of http://localhost:3000/yeyb7ebdbee . How do I go about concatenating root_url to uuid in model concerns.

Here is what I have done below:

app/models/concerns/linkable.rb

module Linkable
  extend ActiveSupport::Concern

  included do
    after_save :create_short_url
    delegate :url_helpers, to: "Rails.application.routes"
    alias :h :url_helpers
  end

  def url
    h.send :"#{route}_url", parameterize
  end

  def route
    # self.class.name.parameterize
    self.model_name.param_key
  end

  def parameterize
    self.id
  end

  protected

  def create_short_url
    update_column :short_url, "#{url}#{uuid}"
  end
end

initializers/host.rb

Rails.application.routes.default_url_options[:host] = 'localhost:3000'

Apparently it, there is no need to parameterize model_name because calling :root_url will always return lowercase and you do not need id since its the root_url you need. By calling self.model_name.param_key or self.class.name.parameterize , the response will result to http://localhost:3000/links/15

Just pass in the :root_url symbol directly in your def url; end def url; end function as seen below and remove these two methods def route; end def route; end and def parameterize; end def parameterize; end and you will be fine:

def url
  h.send :root_url
end

So to be explicit, what you will not have is:

app/models/concerns/linkable.rb

module Linkable
  extend ActiveSupport::Concern

  included do
    after_save :create_short_url
    delegate :url_helpers, to: "Rails.application.routes"
    alias :h :url_helpers
  end

  def url
    h.send :root_url
  end

  protected

  def create_short_url
    update_column :short_url, "#{url}#{uuid}"
  end
end

initializers/host.rb

Rails.application.routes.default_url_options[:host] = 'localhost:3000'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM