CarrierWave - 未定义的方法`image_url'

时间:2015-12-08 17:42:35

标签: ruby-on-rails ruby

所以我还有另一个独特的问题......

我检查了这个TOPIC并且它没有用......我现阶段没有想法......

所以我正在添加上传图片的帖子,然后我试图将其与内容一起显示。

Screenshot with Error

Upload Screenshot

我真的不明白为什么这段代码不起作用......我忘记了什么吗?

show.html.erb

<% provide(:title, @user.name) %>
  <div class="container">
    <div id="content-move">
      <div class="row">
        <aside class="col-md-4">
          <section class="user_info">
            <h1>
              <%= gravatar_for @user %>
              <%= @user.name %>
            </h1>
          </section>
        </aside>
        <div class="col-md-8">
          <% if @user.microposts.any? %>
            <h3>User Posts (<%= @user.microposts.count %>)</h3>
            <div>
              <%= image_tag @microposts.image_url.to_s if @microposts.image_url.present? %>
            </div>
            <ol class="microposts">
              <%= render @microposts %>
            </ol>
          <% end %>
        </div>
      </div>

_micropost_form.html.erb

<%= form_for(Micropost.new) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>
      <div class="field">
        <%= f.text_area :content, placeholder: "Compose new micropost..." %>
      </div>
      <div>
        <%= f.file_field :image %>
      </div>
      <%= f.submit "Post", class: "btn btn-primary" %>
    <% end %>

micropost.rb

class Micropost < ActiveRecord::Base
      belongs_to :user    # Association with User
      has_many :comments

      mount_uploader :image, ImageUploader

      validates :user_id, presence: true
      validates :posttitle, presence: true, length: { maximum: 100 }
      validates :content, presence: true, length: { maximum: 500 }
      validates :posttitle, presence: true, length: { maximum: 140 }

      default_scope -> { order(created_at: :desc) }
    end

1 个答案:

答案 0 :(得分:1)

在这一行:

<%= image_tag @microposts.image_url.to_s if @microposts.image_url.present? %>

@microposts是一组记录,而不是一个微博记录。您可以显示所有图像:

<% @microposts.each do |mp| %>
  <%= image_tag mp.image_url.to_s if @mp.image_url.present? %>
<% end %>

或显示第一个微博的图像:

<%= image_tag @microposts.first.image_url.to_s if @microposts.first.image_url.present? %>

然而,似乎应该在_micropost.html.erb部分(render @microposts)内移动,您可以在其所属的帖子旁边显示图像。