---
title: "Rails的helper_method和Concern"
url: "https://versun.me/rails-helper-method-and-concern"
markdown_url: "https://versun.me/rails-helper-method-and-concern.md"
format: "note"
published: "2024-10-12T13:39:25.000Z"
updated: "2026-01-05T05:29:49.000Z"
collections:
  - "Blog"
site: "Versun"
---

# Rails的helper_method和Concern

今天在做用户认证时，在控制器中一直用`authenticated?`来判断用户是否登陆，但一直不成功。

查了下，发现`authenticated?`是[Authentication Concern](https://github.com/rails/rails/blob/20f5828cacf164f0f53d669b37ba1e4b0f0f8907/railties/lib/rails/generators/rails/authentication/templates/app/controllers/concerns/authentication.rb.tt)的helper\_method方法，  
而helper\_method是暴露给view层使用的，在其它控制器中是不能直接使用的，  
需要在控制器的class下`include Authentication`才可以使用

---

Conern是Rails非常有用的一个概念，在以前，我经常会写多重继承的代码，  
比如“大象”类继承“哺乳动物”类，而“哺乳动物”类又继承自“动物园”类，  
这时候为了兼容，很容易出现“动物园”类里有很多“大象”类和“哺乳动物”类所不需要的方法，  
这就造成代码重用性的问题，而且也不容易维护。  
而Conern允许将共享的代码逻辑封装到单独的可重用的模块中，通常存放在 `app/models/concerns` 或 `app/controllers/concerns` 目录下，  
然后在需要使用这个 Concern 的类中，使用 `include`关键字导入就行了

```
class SomeController < ApplicationController
  include Authentication

  # 现在可以使用 Authentication 中定义的方法和回调
end
```

比如“哺乳动物”类就可以作为一个Conern，“大象”类直接继承自“动物园”类，但可以在“大象”类里include “哺乳动物”类来使用需要的方法。

有点像 接口/协议 的概念，但接口/协议主要是定义/签名，不一定有方法的实现，而Conern直接提供方法的实现，更注重代码的重用性，其它不用考虑
