无法从上传的图像中获取url,has_many关联模型上的未定义方法`url'错误

时间:2013-05-02 22:19:40

标签: ruby-on-rails-3 paperclip rails-activerecord

undefined method `url' for #<GalleryPhoto:0x007f80c05a4ba8>

10:   <%= @gallery.date %>
11: </p>
12: 
13: <%= @gallery.gallery_photos.first.url %>
14: 
15: 
16: <%= link_to 'Edit', edit_gallery_path(@gallery) %>

我正在尝试在rails应用中创建相册系统,在该应用中创建相册并通过回形针将图像上传到相册。我无法使用.url方法在我的显示页面上工作以显示图像。它的设置方式是这样的:

图库模型(有很多gallery_photos)

GalleryPhotos模型(belongs_to gallery)

画廊展示:

<p id="notice"><%= notice %></p>

<p>
  <b>Gallery name:</b>
  <%= @gallery.gallery_name %>
</p>

<p>
  <b>Date:</b>
  <%= @gallery.date %>
</p>

<%= @gallery.gallery_photos.first.url %>


<%= link_to 'Edit', edit_gallery_path(@gallery) %> |
<%= link_to 'Back', galleries_path %>

画廊模型

class Gallery < ActiveRecord::Base
    attr_accessible :date, :gallery_name, :gallery_photos_attributes
    has_many :gallery_photos, :dependent => :destroy

    accepts_nested_attributes_for :gallery_photos

end

gallery_photo模型

class GalleryPhoto < ActiveRecord::Base
    attr_accessible :photo, :caption, :date, :gallery_id

    belongs_to :gallery

    has_attached_file :photo,:styles => { :large => "300x300<", :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

end

图库控制器

  def new
    @gallery = Gallery.new
    @gallery.gallery_photos.build # added this
  end

  def show
    @gallery = Gallery.find(params[:id])
  end

  def create
    @gallery = Gallery.new(params[:gallery])

    respond_to do |format|
      if @gallery.save!
        format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
        format.json { render json: @gallery, status: :created, location: @gallery }
      else
        format.html { render action: "new" }
        format.json { render json: @gallery.errors, status: :unprocessable_entity }
      end
    end
  end

该表是mysql,我通过流浪汉虚拟系统运行它。它正在插入新的,它正在制作它。在新的情况下,它将数据插入到库和gallery_photos的表中。无论我做什么,我都无法得到它。

1 个答案:

答案 0 :(得分:8)

https://github.com/thoughtbot/paperclip开始,url方法属于
has_attached_file :photo,因此检索网址的正确方法是

@gallery.gallery_photos.first.photo.url