Ruby On Rails - Using concerns in controllers

隐身守侯 提交于 2019-12-21 04:36:09

问题


Possible Noob Warning: New to RoR

I am trying to use concerns in RoR. Right now I just have a very simple concern writen

#./app/controllers/concerns/foo.rb
module Foo
  extend ActiveSupport::Concern

  def somethingfoo
    puts "Ayyyy! Foo"
  end
end

When I try and use this concern in my controller I get a undefined method error

#./app/controllers/foo_controller.rb
class FooController < ApplicationController

  include Foo

  def show
    Foo.somethingfoo # undefined method 'somethingfoo' for Foo:Module
    render plain: "Ohh no, It doesnt even show me because of the error above me"
  end
end

To my knowledge somethingfoo should be called but it is not. I have also tried defining somethingfoo in a included do ... end block in the concern but this does not work either.


Is there something I am missing? Can concerns not be used like this with controllers?


回答1:


If you include modules (extended by ActiveSupport::Concern or not), the methods of that module become instance methods of the including class/module.

Your Controller method should hence read

def show
  somethingfoo
  render plain: "Yeah, I'm shown!"
end


来源:https://stackoverflow.com/questions/24394427/ruby-on-rails-using-concerns-in-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!