2

在我的 Rails 3 应用程序中,我有许多带有 boolean field 的模型disabled。在这些模型的控制器中,我使用自定义操作来使用 Ajaxdisable切换字段。disabled

示例(对于客户),

# routes.rb
resources :clients do
  member do
    get :toggle_disable, to: 'clients#disable', as: :disable
  end
end

# clients_controller.rb
def disable
  @client = Client.find(params[:id])
  @client.update_attribute :disabled, !@client.disabled
  render 'clients/update_client', format: :js
end

# update_client.js.erb
$('#client-<%= @client.id %>-details').html("<%= escape_javascript(render 'clients/client', client: @client) %>");

我的应用程序中有至少十个资源的此代码。

问题

我如何着手干燥此代码并为这些布尔字段动态添加操作?我本可以创建一个父控制器或模块,但我不确定我将如何处理视图代码。

我应该能够做这样的事情

#clients_controller.rb
class ClientsController < ApplicationController
  add_toggle_action :disable
end
4

1 回答 1

0

Two main ways to share methods:

  • inheritance: define your action in ApplicationController

  • mixins: add your method in a module and include the module in the appropriate controllers

Since you want only some controllers to get the method, I'll head towards mixin.

Your controller action must use a view with a full path, not relative, something like:

render '/shared/clien/update', format: :js

Lastly, you'll have to define all routes.

于 2012-08-29T12:47:00.797 回答