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
内部拉姆达返回一个零对象。我有点卡住了。需要一些帮助来解决这个问题。以下是我的表单和控制器代码。
# 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
我发现一个问题,类似的事情正在做。但不知何故,我无法得到这项工作。 get parent values in child model
可能重复_for儿童协会验证失败](http://stackoverflow.com/questions/935650/accepts-nested-attributes-for-child-association-validation-failing) – 2014-04-02 22:37:44