【问题标题】:Rails, place to put user input parsingRails,放置用户输入解析的地方
【发布时间】:2014-06-21 09:29:42
【问题描述】:

在我的 Rails 应用程序中有一个视图,其中包含一个简单的用户表单,由一个文本框和一个提交按钮组成。
当用户提交表单时,根据他的输入,创建不同的模型:

class MessageController < ApplicationController
  def create
    if is_foo params[:text]
      Foo.create
    else
      Bar.create 
    end
  end

  def is_foo(text)
    # Here the message gets parsed
    # i.e if text[0] == "M"
  end
end

我的问题是,你认为将“is_foo”逻辑放在 Foo 模型中而不是像这样的控制器中是更好的设计吗?

型号:

class Foo < ActiveRecord::Base
  def self.is_foo(text)
    # Here the message gets parsed
    # i.e if text[0] == "M"
  end
end

控制器:

class MessageController < ApplicationController
  def create 
    if Foo.is_foo params[:text]
      Foo.create
    else
      Bar.create 
    end
  end
end

一方面,模型应该处理逻辑。另一方面,这不是真正的逻辑,它更像是一个输入规则......你们觉得呢?

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord helper


    【解决方案1】:

    Helper

    我会将is_foo 排除在模型之外,因为模型逻辑应该直接与模型有关,而不是确定应该创建/保存哪个模型

    我个人会考虑使用 helper method 进行测试 - 调用文件 ControllerHelper 或类似名称:

    #app/helpers/controller_helper.rb
    class ControllerHelper
      def is_foo? text
        # Here the message gets parsed
        # i.e if text[0] == "M"
      end
    end
    

    这将允许您调用控制器中的帮助程序,使您能够使用逻辑来形成修复:

    #app/controllers/messages_controller.rb
    class MessagesController < ApplicationController
      include ControllerHelper
    
      def create
        model = is_foo?(params[:text]) ? "foo" : "bar"
        model.constantize.send(:create)
      end
    end
    

    【讨论】:

      【解决方案2】:

      我不会像Rich Pecks answer 中提到的那样将其称为ControllerHelper 模块(因为Rails 中的助手与视图相关),而是类似于

      # app/lib/foo_bar_creator.rb
      FooBarCreator = Struct.new(:params) do
        def create
          build.save
        end
      
        def build
          klass.new
        end
      
        def is_foo?
          params[:text] == 'foo'
        end
      
        def klass
          is_foo? ? Foo : Bar
        end
      end
      

      (有些人称这类类为“服务对象”)

      这样我就可以在我的控制器中调用FooBarCreator.new(params).create。

      【讨论】:

        猜你喜欢
        • 2014-03-14
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 2011-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多