Rails 3:属性没有方法错误

时间:2012-05-25 18:50:00

标签: ruby-on-rails

我收到以下错误消息:

NoMethodError in UploadStepsController#update

undefined method `attributes=' for #<ActiveRecord::Relation:0x00000104775c40>


app/controllers/upload_steps_controller.rb:12:in `update'

我目前正在构建一个允许用户使用Wicked Wizard gem上传文件的向导。我在这里缺少什么?

upload_steps_controller.rb

class UploadStepsController < ApplicationController
include Wicked::Wizard
steps :audience, :rewards, :review

def show
    @upload = current_user.uploads
    render_wizard
end

def update
    @upload = current_user.uploads
    @upload.attributes = params[:upload]
    render_wizard @upload
end


end

upload.rb

class Upload < ActiveRecord::Base
attr_accessible :title, :tagline, :category, :genre, :length, :description

belongs_to :user

validates :title, presence: true
validates :tagline, presence: true
validates :category, presence: true
validates :genre, presence: true
validates :length, presence: true
validates :description, presence: true
validates :user_id, presence: true

default_scope order: 'uploads.created_at DESC'
end

新错误

NoMethodError in UploadStepsController#update
undefined method `save' for #<ActiveRecord::Relation:0x0000010159c098>

app/controllers/upload_steps_controller.rb:13:in `update'

3 个答案:

答案 0 :(得分:1)

current_user.uploads是AREL对象。所以你必须指定你想要更新的上传内容。例如,第一次用户上传。

current_user.uploads.first.update_attributes(params[:upload])

或者

@upload = current_user.uploads.find(params[:upload].delete(:id))
@upload.update_attributes(params[:upload])

或所有记录

@upload = current_user.uploads
@upload.update_all(params[:upload])

答案 1 :(得分:0)

试试这个:

@upload.update_attributes(params[:upload])

答案 2 :(得分:0)

@upload = current_user.uploads,它为您提供了uploads对象的数组,但属性方法适用于单个对象。所以你必须应用每个方法

@uploads = current_user.uploads
@uploads.each do | upload|
  upload.update_attributes(params[:upload])
end