我是Ruby和rails的新手。我正在做一个更新表单:硬件数据库中的所有者值。在使用自定义视图名称transfer.html.erb时,我的表单代码如下所示。
<%= form_for @hardware, :url => do_transfer_path do |f| %>
这是我在hardwares_ranfers_controller.rb 中的自定义控制器
def transfer
@hardware = Hardware.find(params[:id])
if current_user.user_lvl == 0
@users = User.order(:user_lvl)
else
@users = User.where(:refer => current_user.id)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @hardwares }
end
end
end
def do_transfer
# transfer_user = User.where(:id => @hardware.owner).email
# TransferLog.create([:user_id => current_user.id, :hardware_id => @hardware.id])
if @hardware.update_attributes(params[:hardware])
format.html { redirect_to users_url, notice: "Hardware was successfully transfer"}
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @hardware.errors, status: :unprocessable_entity }
end
end
我得到的错误是HardwareTransfersController#do_transfer中的NoMethodError未定义的方法update_attributes' for nil:NilClass
Aplication Traces
app/controllers/hardwares_transfers_controller.rb:23:in
do_transfer'
参数
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"vkwKyuS4eviRN1ogrpOcGh1Y5OBNX0wiBzpV8taNkq0=",
"hardware"=>{"owner"=>"3"},
"commit"=>"Transfer Hardware"}
我的路线.rb
match "hardwares_transfers/" => "hardwares_transfers#do_transfer" , :as => :do_transfer
get "hardwares_transfers/:id/transfer" => "hardwares_transfers#transfer", :as => :transfer_hardwares
耙路>
do_transfer /hardwares_transfers(.:format) hardwares_transfers#do_transfer
transfer_hardwares GET /hardwares_transfers/:id/transfer(.:format) hardwares_transfers#transfer
hardwares GET /hardwares(.:format) hardwares#index
POST /hardwares(.:format) hardwares#create
new_hardware GET /hardwares/new(.:format) hardwares#new
edit_hardware GET /hardwares/:id/edit(.:format) hardwares#edit
hardware GET /hardwares/:id(.:format) hardwares#show
PUT /hardwares/:id(.:format) hardwares#update
DELETE /hardwares/:id(.:format) hardwares#destroy
您需要
def do_transfer
@hardware = Hardware.find(params[:id])
...
end
我还将借此机会指出,您可能会以更REST的方式构建
查找硬件项:
def do_transfer
@hardware = Hardware.find(params[:id])
...
end
和更改路线。rb:
match "hardwares_transfers/:id" => "hardwares_transfers#do_transfer" , :as => :do_transfer
错误为NoMethodError in HardwaresTransfersController#do_transfer
nil:NilClass的未定义方法update_attributes'。
正如错误所说,Rails试图在nil:NilClass上调用update_attributes,这意味着您的@hardware
对象是nil
所以,你应该通过初始化它
@hardware = Hardware.find(params[:id])
你应该经常观察错误,并思考为什么会出现这种错误,这将帮助你更好地学习。