0

我正在使用 CarrierWave 作为我的相册,并且我正在尝试进行设置,以便我可以防止用户最多只能将 5 张照片上传到他们的画廊。但是,当单击页面标题为“PhotosController#create 中的 NoMethodError”的“上传照片”按钮时,我收到了“未定义的方法‘用户’”错误

照片.rb:

class Photo < ActiveRecord::Base
  attr_accessible :title, :body, :gallery_id, :name, :image, :remote_image_url
  belongs_to :gallery
  mount_uploader :image, ImageUploader

    LIMIT = 5

    validate do |record|
      record.validate_photo_quota
    end

    def validate_photo_quota
      return unless self.user
      if self.user.photos(:reload).count >= LIMIT
        errors.add(:base, :exceeded_quota)
      end
    end
end

照片_控制器:

class PhotosController < ApplicationController

  def new
    @photo = Photo.new(:gallery_id => params[:gallery_id])
  end

  def create
    @photo = Photo.new(params[:photo])
    if @photo.save
      flash[:notice] = "Successfully created photos."
      redirect_to @photo.gallery
    else
      render :action => 'new'
    end
end

  def edit
    @photo = Photo.find(params[:id])
  end

  def update
    @photo = Photo.find(params[:id])
    if @photo.update_attributes(paramas[:photo])
      flash[:notice] = "Successfully updated photo."
      redirect_to @photo.gallery
    else
      render :action => 'edit'
    end
  end

  def destroy
    @photo = Photo.find(params[:id])
    @photo.destroy
    flash[:notice] = "Successfully destroyed photo."
    redirect_to @photo.gallery
  end
end

我以为我以前已经定义了用户,除非必须为每个控制器完成它?

4

1 回答 1

2

你正在调用self.user模型Photoself在这种情况下,关键字代表photo. 根据您的定义, aphoto属于 a gallery,因此,user不能从照片中调用。

如果 agallery属于用户,那么您应该能够调用self.gallery.user以选择该照片的用户所有者。


您还可以定义has_many :through关联,以便您可以直接从该照片调用用户,或检索该用户的所有照片。

这可以按照文档来完成。在你的情况下:

class User < ActiveRecord::Base
  has_many :galeries
  has_many :photos, :through => :galeries
end

class Photo < ActiveRecord::Base
  belongs_to :user, :through => :gallery
  belongs_to :gallery
end

class Gallery < ActiveRecord::Base
  belongs_to :user
  has_many :photos
end

然后你应该能够打电话photo.user并获得图片的所有者。

于 2013-03-19T13:58:08.803 回答