nil的未定义方法`keys':包含Paperclip之后的NilClass

时间:2014-08-09 13:04:18

标签: ruby-on-rails ruby ruby-on-rails-4

我是新的ruby on rails并且在我加入papperclip后,如果我尝试更换照片,我会收到此错误。

如果我更改了paperclip`s github上的README.md中的create方法:

def create
  @hotel = Hotel.create( hotel_params )
end

private

# Use strong_parameters for attribute whitelisting
# Be sure to update your create() and update() controller methods.

def hotel_params
  params.require(:hotel).permit(:name, :photo, :room_description, :price_for_room, :breakfast, :country, :state, :city, :street)
end

我在Create方法中遇到同样的错误。你可以帮帮我吗?我在这里缺少什么?

  • Ryby 1.9.3
  • Rails 4
  • Paperclip 4.2.0

Error screenshot

hotels_controller.rb

class HotelsController < ApplicationController
  before_action :signed_in_user, except: [:index, :show]


  def index
     @hotels = Hotel.paginate(:page => params[:page], :per_page => 5)
  end

  def show
    @hotel = Hotel.find(params[:id])
    @comments = @hotel.comments
  end

  def new
    @hotel = Hotel.new
  end

  def edit
    @hotel = Hotel.find(params[:id])
  end

  def create
    @hotel = current_user.hotels.new(params[:hotel])
    if @hotel.save
      redirect_to @hotel, notice: "Hotel was successfully created."
    else
      render "new"
    end
  end

  def update
     @hotel = Hotel.find(params[:id])
    if @hotel.update_attributes(params[:hotel])
     redirect_to @hotel, notice: "Hotel was successfully updated."
    else
     render "edit"
    end
  end

  def destroy
    @hotel = Hotel.find(params[:id])
    @hotel.destroy
    redirect_to hotels_url
  end
end

hotel.rb

  class Hotel < ActiveRecord::Base
    has_many :comments
    belongs_to :user
    has_many :ratings
  has_many :raters, :through => :ratings, :source => :users

    validates :name, presence: true, length: { minimum: 5 }
    validates :room_description, presence: true
  validates :price_for_room, presence: true, numericality: true
  validates_associated :comments

  has_attached_file :photo, :styles => { :medium => "500x500>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/

    def update_average_rating
    @value = 0
    self.ratings.each do |rating|
      @value = @value + rating.value
    end
    @total = self.ratings.size


    update_attributes(average_rating: @value.to_f / @total.to_f)
  end
end

1 个答案:

答案 0 :(得分:0)

当您使用Rails4时,您的update操作应该是这样的

def update
     @hotel = Hotel.find(params[:id])
    if @hotel.update_attributes(hotel_params) #Here
     redirect_to @hotel, notice: "Hotel was successfully updated."
    else
     render "edit"
    end
  end