# 自定义主页以根据用户兴趣显示话题

**URL:** <https://meta.discourse.org/t/customizes-the-homepage-to-show-topics-based-on-user-interests/311283>\
**Category:** Development\
**Created:** [2024 年6 月 9 日 07:28 UTC](https://meta.discourse.org/t/customizes-the-homepage-to-show-topics-based-on-user-interests/311283 "2024-06-09T07:28:35Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

作者： ![kokoloman001](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kokoloman001/32/389438_2.png) [@kokoloman001](https://meta.discourse.org/u/kokoloman001)\
发布日期： [2024 年6 月 9 日 10:24 UTC](https://meta.discourse.org/t/customizes-the-homepage-to-show-topics-based-on-user-interests/311283/3 "2024-06-09T10:24:00Z")

</div>

> [@hello-smile6](#):
>
> `/preferences/interests` 在哪里实现？

我认为，为了处理用户兴趣并将其集成到用户偏好设置中，必须创建所需的路由、控制器操作和模板。

不过，这只是我的看法，而且只是初步设计。我还没有开始着手构建。如果我尝试，可能会不顺利。

**为用户偏好设置添加路由** ：  
- 添加一个路由来处理对 `/u/:username/preferences/interests` 的请求。

````
```ruby
# plugins/custom_homepage/config/routes.rb
Discourse::Application.routes.append do
  get '/u/:username/preferences/interests' => 'custom_homepage#interests', constraints: { username: /[^\\/]+/ }
end
```

````

**创建控制器操作** ：  
- 定义一个控制器来处理请求并获取用户的兴趣。

````
```ruby
# plugins/custom_homepage/app/controllers/custom_homepage_controller.rb
class CustomHomepageController < ApplicationController
  requires_login
  
  def interests
    username = params[:username]
    user = User.find_by(username: username)
    
    if user
      render json: {
        interests: user.custom_fields['interests']
      }
    else
      render json: { error: 'User not found' }, status: 404
    end
  end
end
```

````

**在用户偏好设置中添加兴趣字段** ：  
- 修改用户偏好设置模板以包含一个兴趣输入框。

````
```html
<!-- plugins/custom_homepage/assets/javascripts/discourse/connectors/user-preferences/interests.hbs -->
<div class="control-group">
  <label class="control-label">{{i18n 'user.preferences.interests'}}</label>
  <div class="controls">
    {{input value=model.custom_fields.interests class="form-control"}}
  </div>
</div>
```

````

**扩展序列化器** ：  
- 扩展用户序列化器以包含兴趣字段。

````
```ruby
# plugins/custom_homepage/plugin.rb

after_initialize do
  User.register_custom_field_type('interests', :string)
  
  add_to_serializer(:current_user, :interests) do
    object.custom_fields['interests']
  end

  add_to_serializer(:admin_detailed_user, :interests) do
    object.custom_fields['interests']
  end
end
```

````

**修改用于处理兴趣的 JavaScript** ：  
- 使用 JavaScript 来获取兴趣并将其保存到用户配置文件中。

````
```javascript
// plugins/custom_homepage/assets/javascripts/discourse/initializers/custom-homepage.js.es6

import { withPluginApi } from 'discourse/lib/plugin-api';

export default {
  name: 'custom-homepage',
  initialize(container) {
    withPluginApi('0.8', api => {
      api.modifyClass('controller:preferences/account', {
        save() {
          const interests = this.model.custom_fields.interests;
          this.model.save().then(() => {
            fetch(`/u/${this.model.username}/preferences/interests`, {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': Discourse.CSRFToken
              },
              body: JSON.stringify({ interests })
            }).then(response => response.json()).then(() => {
              this.flash('Your preferences have been saved.');
            });
          });
        }
      });
    });
  }
};
```

````

1. **处理 PUT 请求** ：

---

_[View the full topic](https://meta.discourse.org/t/customizes-the-homepage-to-show-topics-based-on-user-interests/311283)._
