ユーザーのための通知を生成するカスタムクラスを作成したいと思います。私の質問は、link_to
経由で通知テキストのリソースへのリンクを生成する方法です。ActionController :: Base以外のクラスにActionView :: Helpersを正しく組み込む方法は?
:I create_text
方法で表示されますMaker
クラスにActionView::Helpers::UrlHelper
とRails.application.routes.url_helpers
を含め、エラーをfollwing持っていた、:
thisから続く命令と「どのようにモデルにlink_to
を使用する」のような同様の答えをlink_to
を使用しよう:
EmployeesControllerTest#test_company_vacancy_daily:
NameError: undefined local variable or method `controller' for #<Notifies::Maker:0x000000069ae218>
/usr/local/rvm/gems/ruby-2.2.5/gems/actionview-5.0.0.1/lib/action_view/routing_url_for.rb:132:in `optimize_routes_generation?'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/route_set.rb:192:in `optimize_routes_generation?'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/route_set.rb:172:in `call'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/route_set.rb:295:in `block (2 levels) in define_url_helper'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionpack-5.0.0.1/lib/action_dispatch/routing/polymorphic_routes.rb:262:in `handle_model_call'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionview-5.0.0.1/lib/action_view/routing_url_for.rb:116:in `url_for'
/usr/local/rvm/gems/ruby-2.2.5/gems/actionview-5.0.0.1/lib/action_view/helpers/url_helper.rb:196:in `link_to'
/app/lib/notifies.rb:32:in `block in create_text'
/app/lib/notifies.rb:32:in `map!'
/app/lib/notifies.rb:32:in `create_text'
/app/lib/notifies.rb:38:in `run'
/app/test/controllers/notifications_test.rb:167:in `block (2 levels) in <class:EmployeesControllerTest>'
/usr/local/rvm/gems/ruby-2.2.5/gems/activesupport-5.0.0.1/lib/active_support/testing/assertions.rb:71:in `assert_difference'
/app/test/controllers/notifications_test.rb:166:in `block in <class:EmployeesControllerTest>'
そして、私のコードは次のとおりです。
module Notifies
class Maker
include ActionView::Helpers::UrlHelper
include Rails.application.routes.url_helpers
def initialize(model, kind)
@model = model
@kind = kind
case @model.class.to_s
when 'Company'
@to = @model.admin
when 'Employee'
@to = @model
end
end
def build_list
present = Time.now.utc
past = present - 24.hours
popularities = Popularity.where(to: @model.entity.id).select do |e|
e.updated_at.utc.between?(past, present)
end
popularities.map! { |p| p.from_entity.turn }
end
def create_text(popularities = build_list)
text = 'Those users interested in your contacts: '
popularities.map! { |p| link_to p.full_name, p }
text + popularities.join(', ')
end
def run
popularities = build_list
text = create_text(popularities)
@to.notify(kind: @kind, text: text) if popularities.any?
end
end
end
ありがとうございますが、これはリンクが付いた1行のテキストのみを生成するには複雑すぎるようですので、私はいくつかの調査を行い、答えを見つけました。 – Max