我有一个模特:
class Scr < ActiveRecord::Base
def self.find_scrs
find(:all, :order => "id")
end
end
查看(表单):
<div class="scr-form">
<fieldset>
<% form_for :scr, :url => { :action => :save_scr } do |form| %>
<p>
<label for="scr_id">Id:</label>
<%= form.text_field :id, :size => 40 %>
</p>
<p>
<label for="scr_description">Description:</label>
<%= form.text_area :description, :rows => 3, :cols => 40 %>
</p>
<%= submit_tag "Save", :class => "submit" %>
<% end %>
</fieldset>
</div>
和控制器:
class InboxController < ApplicationController
def index
@scrs = Scr.find_scrs
end
def add_scr
end
def save_scr
@src = Scr.new(params[:scr])
puts "=============================="
@a = params[:scr]
puts @a
puts "=============================="
@scr.save
end
end
我填写表单中的字段,按“保存”按钮并收到错误:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.save
/home/demas/artefacts/dev/study/ruby/rails/tracker/app/controllers/inbox_controller.rb:15:in `save_scr'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/base.rb:1331:in `perform_action'
/usr/lib/ruby/gems/1.9.1/gems/actionpack-2.3.8/lib/action_controller/filters.rb:617:in `call_filters'
...
Request
Parameters
{"authenticity_token"=>"m/QBN85+5Kj+Qewtl29mBl5kBtSBr1+Ixv4jxTq6Rfk=",
"scr"=>{"id"=>"as",
"description"=>"sa"},
"commit"=>"Save"}
正如我所见,Rails无法创建Scr类的实例。为什么呢?
答案 0 :(得分:3)
def save_scr
@scr = Scr.new(params[:scr])
puts "=============================="
@a = params[:scr]
puts @a
puts "=============================="
@scr.save
end