在模型上编写方法或将模型作为参数传递

时间:2014-10-13 21:59:34

标签: ruby-on-rails ruby modal-dialog class-method

有人可以解释如何确定是否应该在模态上定义模态类实例的方法,还是单独将模态实例作为参数传入?

以下是一个例子:

我有一个名为VisitorMarketing的模态。我需要定义方法start_marketingstop_marketing

我可以在访问者模式中创建它们,如下所示:

  class Visitor < ActiveRecord::Base
    has_many :marketing

    def start_marketing(options)
      # massage the passed in attribute here
      # then make api calls
      # then do some business logic here
      self.marketing.create options
    end

    def stop_marketing(options)
      # massage the passed in attribute here
      # then make api calls
      # then do some business logic here
      marketing = self.marketing.find options
      marketing.update_attributes {:mark_stopped => true}
    end
  end

或者我可以在营销模式中创建它们:

  class Marketing < ActiveRecord::Base
    belongs_to :visitor

    def self.start(visitor, options)
      # massage the passed in attribute here
      # then make api calls
      # then do some business logic here
      Marketing.create {:visitor_id => visitor.id}.merge(options)

    end

    def self.stop(visitor,options)
      # massage the passed in attribute here
      # then make api calls
      # then do some business logic here
      marketing.find_by_visitor_id_and_id options[:id], options[:visitor_id]
      marketing.update_attributes {:mark_stopped => true}
    end
  end

这些只是突出我感到困惑的一个例子。实际上,除了更新记录之外,这些方法还会在实例上做更多的事情。

1 个答案:

答案 0 :(得分:0)

如果我理解你的问题。第一个版本更像是rails方式。首先,您正在使用内置的关联方法,并避免在第二个示例中传递ID。

如果没有关于您遇到的确切问题的详细信息,我无法提供明确的答案。