2017-07-28 26 views
-1

QuoteRequest has_one Quote belong_to QuoteRequest。下面是我想在我的Rails应用程序来实现的任务:最佳实践#创建一个Class2的实例并从Class1上调用它的逻辑?

  1. QuoteRequestsController#create.save的IT调用QuotesController#create(跳过QuotesController#新的,因为没有创建报价所需的视图或用户输入的,只是一个内部刮削任务)。
  2. QuotesController#create一个Quote.new实例已调用它Quote#gather_quote方法
  3. `Quote.gather_quote出门的Watir抓取和保存价值,以实例变量,这successfullly抓取并在控制台测试保存到实例变量所需的值。
  4. 然后Quote.save保存实例,它的Watir,Quote#gather_quote,收集实例变量到数据库。数据库中存在正确的列。

但是我有,我想,麻烦变量传递/范围,或从QuoteRequestController#create行动的地方在我的代码迁移到QuoteController#create

  • QuoteRequest实例保存正常。
  • 报价实例正在保存,但没有通过引用#gather_quote创建的实例变量。我认为代码甚至不会运行Quote.gather_quote方法。

你能不能帮我了:

一)找出什么不与现行做法的工作和

B)上实现的更好的方式告知什么我想,如果你认为有一个。

谢谢。

quote_requests_controller.rb

class QuoteRequestsController < ApplicationController 
before_action :authenticate_user!, only: [ :new, :create, :show, :index ] 

    def new 
    @company = current_user.company 
    @quote_request = QuoteRequest.new 
    end 

    def create 
    @company = current_user.company 
    @quote_request = @company.quote_requests.build(quote_request_params) 
    if @quote_request.save 
     Quote.create({ quote_request_id: @quote_request.id}) 
     render :nothing => true 
    end 
    end 
end 

quote_request.rb

class QuoteRequest < ApplicationRecord 
    belongs_to :company 
    has_one :quote 
end 

quote_controller.rb

class QuotesController < ApplicationController 

    def create 
    @quote = Quote.new({ quote_request_id: @quote_request.id }) 
    @quote.get_quote 

    if @quote.save 
     render 'show' 
    end 
    end 

    def show 
    render 'show' 
    end 
end 

quote.rb

class Quote < ApplicationRecord 
    require 'watir' 
    attr_accessor :lives, :salary, :frequency 
    attr_reader :url, :username, :password 
    belongs_to :quote_request 

    def initialize(args) 
    @url = 'url' #required by Watir as part of the #gather_quote 
    @username = 'me' 
    @password = 'password' 
    super 
    end 


    def gather_quote 
    browser_session 
    login 
    start_quote 
    complete_form 
    scrape_results 
    end 
end 
+0

你试图从另一个控制器调用控制器方法? – jvillian

+0

不好意思!在创建一个控制器(QuoteRequest)时,我想要创建该对象,然后转到另一个控制器(引用)a)builld这个第二个(Quote)类的新实例,然后b)在此新操作上运行一些爬行逻辑第二类实例,然后c)保存第二个类实例。 (并且没有第一个控制器的#create呈现的视图,只需执行上面的a),b)和c)然后第二个控制器呈现#show)。 – jbk

+0

你究竟在爬行什么? – jvillian

回答

0

您似乎对控制器的基本知识有缺陷。

控制器只是处理单个请求 - 响应循环的机制。在一个请求 - 响应周期内,您不会“转向”其他控制器。而且您不会从其他控制器调用控制器。它只是不这样工作。

此外,控制器与模型没有紧密耦合。也就是说,您可以使用(实例化,更新,保存等)QuoteRequestController中的Quote模型。

要编排跨多个模型类的活动(并执行诸如抓取外部网站之类的内容),您应该查看普通的旧红宝石对象(有时称为PORO)。具体来说,谷歌服务对象和服务模式。最后,我不知道你的抓取需要多长时间,但是如果这需要大量时间,你可能需要查看后台作业(以避免请求超时和/或废话的用户体验)。

+0

感谢您通过对控制器和MVC的理解来进行现实检查,我会听取您的建议,研究PORO服务对象和相关模式。我认为我的问题的一部分是,我已经将QuoteRequest与Quote分开(可能更好的命名; QuoteResponse),“爬网”现在发生在Quote中,预计稍后重构,这促使我的“跨控制器”尝试creatiions。无论如何,我会得到这个重构和正确组织,然后发布工作代码回到这个Q. – jbk