QuoteRequest
has_one Quote
belong_to QuoteRequest
。下面是我想在我的Rails应用程序来实现的任务:最佳实践#创建一个Class2的实例并从Class1上调用它的逻辑?
- 后
QuoteRequestsController#create
.save
的IT调用QuotesController#create
(跳过QuotesController#新的,因为没有创建报价所需的视图或用户输入的,只是一个内部刮削任务)。 - 在
QuotesController#create
一个Quote.new
实例已调用它Quote#gather_quote
方法 - `Quote.gather_quote出门的Watir抓取和保存价值,以实例变量,这successfullly抓取并在控制台测试保存到实例变量所需的值。
- 然后
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
你试图从另一个控制器调用控制器方法? – jvillian
不好意思!在创建一个控制器(QuoteRequest)时,我想要创建该对象,然后转到另一个控制器(引用)a)builld这个第二个(Quote)类的新实例,然后b)在此新操作上运行一些爬行逻辑第二类实例,然后c)保存第二个类实例。 (并且没有第一个控制器的#create呈现的视图,只需执行上面的a),b)和c)然后第二个控制器呈现#show)。 – jbk
你究竟在爬行什么? – jvillian