class Query < ActiveRecord::Base
#relations
has_one :r_job
accepts_nested_attributes_for :r_job
end
class RJob < ActiveRecord::Base
belongs_to :query
validates_presence_of :analysis_type, :if => lambda {|job| job.query.process_r_job}
end
我有一个用于创建查询和 r_job 的嵌套表单。我在查询对象中有一个布尔字段,我必须根据查询对象中的布尔值对 r_job 进行一些验证。我正在尝试使用上面的代码执行此操作,但我得到了一个无方法错误。
NoMethodError (undefined method `process_r_job' for nil:NilClass):
app/models/r_job.rb:3:in `block in <class:RJob>'
app/controllers/queries_controller.rb:9:in `create'
我挖了一下,我发现,job.query
内部 lambda 正在返回一个 nil 对象。我有点坚持这一点。需要一些帮助来解决这个问题。下面是我的表单和控制器代码。
# app/views/queries/new.html.haml
=form_for @query, {:html => {:class=>"form-horizontal"}}do |f|
- if @query.errors.any?
.alert.alert-error
%h4.alert-heading Error(s)!
- @query.errors.full_messages.each do |msg|
%p= msg
=render "query_form", :f => f
%fieldset
=f.fields_for :r_job do |builder|
=render "r_job_form", :f => builder
%button.btn.btn-primary.small Go
#app/controller/queries_controller.rb
class QueriesController < ApplicationController
def new
@query = Query.new
@query.build_r_job
end
def create
@query = Query.new(params[:query])
if @query.save
redirect_to root_path, :notice => "Yay!! Your query is running. You can download the CSV once the query finishes."
else
flash.now[:error] = "Oops, the query cannot be saved!!"
render :new
end
end
end
我发现一个问题正在做类似的事情。但不知何故,我无法得到这项工作。 在子模型中获取父值