How to use url_helpers in rails 4.2?

2019-09-21 05:33发布

I am trying to build some links for my datatable and been struggling with it for the past 4 hours.

This is my current code:

class UsersDatatable < TemplateDatatable
  def data
    users.map do |user|
      [
        user.id,
        user.nome,
        user.email,
        user.provider.camelize,
        links(user)
      ]
    end
  end

  def links(user)
    html = link_to url_helpers.edit_user_registration_path(user), class: "btn btn-mini btn-info", "data-rel" => "tooltip", title: "Editar", "data-placement" => "top" do
      content_tag(:i, '', class: "icon-edit")
    end.html_safe
  end
end

class TemplateDatatable
  include ActionView::Helpers::FormTagHelper
  include ActionView::Context

  delegate :params, to: :@view
  delegate :url_helpers, to: 'Rails.application.routes'
end

And this is the error I keep getting:

ArgumentError (arguments passed to url_for can't be handled. Please require routes or provide your own implementation)

Every thing I try to build my link from my model, doesn't work. I ran through rails issues on github and couldn't find nothing about this.

Any help?

edit:

I also tried the first solution proposed and still it doesn't work. I get the same error. This is what I did:

class User < ActiveRecord::Base
  include Rails.application.routes.url_helpers

  def edit_registration_path
    edit_user_registration_path(self)
  end
end

def links(user)
  html = link_to user.edit_registration_path, class: "btn btn-mini btn-info", "data-rel" => "tooltip", title: "Editar", "data-placement" => "top" do
  content_tag(:i, '', class: "icon-edit")
end.html_safe

This is not a simple thing where you add the url inside a model and call it. This is different than the said duplication.

1条回答
【Aperson】
2楼-- · 2019-09-21 06:01

You need to include this in you class:

class User < ActiveRecord::Base
  include Rails.application.routes.url_helpers

  def base_uri
    user_path(self)
  end
end

User.find(1).base_uri # => "/users/1"

Check for refference:

查看更多
登录 后发表回答