【问题标题】:undefined method `url' for #<ActiveRecord::Associations::CollectionProxy []>#<ActiveRecord::Associations::CollectionProxy []> 的未定义方法“url”
【发布时间】:2016-11-18 10:06:53
【问题描述】:

这是我的Post 控制器创建操作:

def create
  @user = current_user
  @post = @user.posts.create(post_params)

  respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
      format.json { render :show, status: :created, location: @post }
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end

私人:

def post_params

params.require(:post).permit( :title, :description, :size, images_attributes [:id,:image,:imageable_id,:imageable_type])

结束

结束

这是show.html.erb

(<%= image_tag @post.images.url %>)

这是Post 型号:

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :images, as: :imageable
  accepts_nested_attributes_for :images
end

这是Image 型号:

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  mount_uploader :image, ImageUploader
end

【问题讨论】:

    标签: ruby-on-rails carrierwave


    【解决方案1】:

    看起来您正在使用 Carrierwave 并将其安装在 Image 模型的 image 属性上。因此,这样的事情可能会起作用:

    <% @post.images.each do |image| %>
      <%= image_tag image.image_url(:original) %>
    <% end %>
    

    您可以将 :original 替换为您的载波上传器文件创建的任何版本

    【讨论】:

    • 如何查看carrierwave文件创建的版本?
    • 默认情况下,Carrierwave 将创建一个名为 :original 的版本,因此上面的代码应该可以正常工作,您可以通过查看 app/uploaders/image_uploader.rb 来了解 Carrierwave 创建的其他版本
    • 在我的 image_uploader 中,版本是 thumb。我将其替换为 :original 但图像不显示 ''
    • 您上传图片了吗?我还可以在您的 post_params 方法中看到一个错字,它应该在 images_attributes 键之后有一个冒号,如下所示:images_attributes: [:id,:image,:imageable_id,:imageable_type]
    • 您可能需要重新上传图片
    【解决方案2】:

    &lt;%= image_tag @post.images %&gt; 给出了一个collections of images 属于@post

    要渲染帖子的图像,请执行以下操作:

    <% @post.images.each do |img| %>
      <%= image_tag img.url %>
    <% end %>
    

    【讨论】:

    • 图片不显示。
    猜你喜欢
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多