fahad
fahad

Reputation: 21

undefined method `url' for #<ActiveRecord::Associations::CollectionProxy []>

This is my Post controller create action:

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

private:

def post_params

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

end

end

This is show.html.erb:

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

This is the Post model:

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

This is the Image model:

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

Upvotes: 0

Views: 1579

Answers (2)

stephenmurdoch
stephenmurdoch

Reputation: 34643

It looks like you're using Carrierwave and have mounted it on the image attribute of the Image model. Therefore something like this will likely work:

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

You can replace :original with whatever versions your carrierwave uploader file creates

Upvotes: 1

mrvncaragay
mrvncaragay

Reputation: 1260

<%= image_tag @post.images %> gives a collections of images belongs to the @post

To render the images of post do this:

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

Upvotes: 0

Related Questions