在我们的Rails 3.1.0应用程序中,我们需要在create和update中修改传递给rfq控制器的params。例如,我们想要在input_by_id下记录当前用户ID。我们做的是:
@rfq.input_by_id = session[:user_id]
它按预期工作。此外,当need_report字段为false时,则report_language字段应为nil。我们决定在rfq控制器中添加以下行,以确保在need_report为false时将nil传递给report_language:
@rfq.report_language = nil unless params[:need_report]
但是,由于数据验证失败,此添加会导致rspec案例失败(在控制器的创建/更新中)。但是,当我们启动应用程序时,当need_report为false时,它在没有保存report_language的情况下表现良好。我想知道上面的行是不是使用params [:need_report]进行@rfq更新的正确方法。
非常感谢。
更新:
控制器代码:
def create
if has_create_right?
@rfq = Rfq.new(params[:rfq], :as => :roles_new )
@rfq.input_by_id = session[:user_id]
#save sales_id selected
if sales? && member? && !team_lead?
@rfq.sales_id = session[:user_id]
end
#view page may carry the hidden report language even if need_report == false
@rfq.report_language = nil unless params[:need_report]
#save into join table rfqs_standards
params[:rfq][:standard_ids].each do |sid|
@rfq.standards << Standard.find(sid.to_i) if !sid.nil? && sid.to_i > 0
end unless params[:rfq][:standard_ids].nil?
#save into join table rfqs_test_items
params[:rfq][:test_item_ids].each do |tid|
@rfq.test_items << TestItem.find(tid.to_i) if !tid.nil? && tid.to_i > 0
end unless params[:rfq][:test_item_ids].nil?
if @rfq.save!
redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
else
flash.now[:error] = "RFQ not saved!"
render 'new'
end
else
redirect_to URI.escape("/view_handler?index=0&msg=No rights!")
end
end
添加@rfq.report_language = nil unless params[:need_report]
it "should be successful for corp head" do
session[:corp_head] = true
session[:user_id] = 1
s = Factory(:standard)
rfq = Factory.attributes_for(:rfq, :need_report => true, :report_language => 'EN')
rfq[:standard_ids] = [s.id] # attach standard_id's to mimic the POST'ed form data
get 'create', :rfq => rfq
#response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
response.should render_template('new')
end
答案 0 :(得分:1)
问题在于你根本没有看到正确的价值。
get 'create', :rfq => rfq
会产生类似{:rfq => {...}}
所以你需要@rfq.report_language = nil unless params[:rfq][:need_report] == 'true'