Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails - Using concerns in controllers

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?

like image 788
Noah Huppert Avatar asked Jun 24 '14 19:06

Noah Huppert


People also ask

What is concern in Ruby on Rails?

DHH. A Rails Concern is a module that extends the ActiveSupport::Concern module. Concerns allow us to include modules with methods (both instance and class) and constants into a class so that the including class can use them. A concern provides two blocks: included.

What does ActiveSupport :: concern do?

ActiveSupport's Concern module allows us to mix in callbacks, class and instance methods, and create associations on target objects. This module has an included method, which takes a block, as well as an append_features method and class_methods block, which you can read about in the source code.

What is the difference between module and concern?

Concern can appear somewhere as model, controller and at here you can write module for yourself. And with general module is write in lib folder. Both can be used by way include or extend into a class.

What decides which controller receives which requests Ruby on Rails?

Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions.


1 Answers

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
like image 150
DMKE Avatar answered Oct 16 '22 06:10

DMKE