从控制器调用静态方法并更新该类的实例 - 获取 AR::Association::HasOneAssociation 的未定义方法

问题描述 投票:0回答:1

我的问题:

正确的结构应该是什么?我已经多次尝试重新设计,但不断遇到紧耦合问题。

相关信息:

我正在为一些第三方软件编写一个新端点。 它将接收一个有效负载,然后我将其传递到我的 Subscription 类的静态方法中。 从那里我想查找与有效负载相关的订阅,建立它的实例,然后根据我的类的其余信息执行更新。我遇到了一个错误,内容如下:

undefined method update for ActiveRecording::Association::HasOneAssociation

端点控制器:

class Api::V2::EndpointController < Api::V5::BaseController
    def connect
        data = decode(request.body.read)
        Subscription.static_method(data)
    end
end

订阅模式:

class Subscription < ActiveRecord::Base

    def self.static_method(data)
        @subscription = Subscription.find_by_id(data.subscription_id)
        @subscription.update(data)
    end
end

订阅控制器:

class SubscriptionsController < ApplicationController
    def update
        #execute update
    end
end
ruby-on-rails ruby ruby-on-rails-3
1个回答
0
投票

将代码移入模型一开始并不是一个好主意。控制器需要检查更新是否成功并做出相应响应。除了你传入的内容之外,模型也没有上下文的概念,并且已经承担了过多的责任。

我会以最直接的方式在控制器中编写这段代码。

# @todo setup the correct inflections in config/initializers/inflections.rb
# @see https://github.com/rubocop/ruby-style-guide#camelcase-classes
# @see https://github.com/rubocop/ruby-style-guide#namespace-definition
module API
  
  module V2 < 
    # @todo Write a high level description of the what the responsibility of this class is.
    # the name itself is pretty smelly. 
    # "Endpoint" is very vague - every controller method is an endpoint.
    # Why is this inheriting from a different version of the API?    
    class EndpointController < API::V5::BaseController
      # @todo write a description of the purpose of this method
      # @todo document the route that this method corresponds to
      def connect
        data = decode(request.body.read) # WTF is this? 
        # .find will raise an exception if the id is not valid
        # Rails will catch this and return a 404.
        @subscription = Subscription.find(data.subscription_id)
        if @subscription.update(data)
          head :ok # or provide some other response
        else
          head :unprocessable_entity
        end
      end
    end
  end
end

如果您后来发现重复此代码两次以上,则添加抽象,例如服务对象。

© www.soinside.com 2019 - 2024. All rights reserved.