Ruby On Rails - 在控制器中使用关注点 [英] Ruby On Rails - Using concerns in controllers

查看:47
本文介绍了Ruby On Rails - 在控制器中使用关注点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的菜鸟警告: RoR 新手

我正在尝试在 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

据我所知 somethingfoo 应该被调用,但它不是.我还尝试在关注的 included do ... end 块中定义 somethingfoo ,但这也不起作用.


有什么我想念的吗?控制器不能像这样使用关注点吗?

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?

推荐答案

如果你包含模块(由 ActiveSupport::Concern 扩展或不包含),该模块的方法将成为包含的实例方法类/模块.

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

这篇关于Ruby On Rails - 在控制器中使用关注点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆