无法上传图像rails并发生错误

时间:2017-10-03 19:25:22

标签: ruby ruby-on-rails-5

我想使用gem'carrierwave'将图像上传到我的localhost,我有绘画和画廊控制器,如下面的代码

绘画控制器

class PaintingsController < ApplicationController
  def index
    @paintings=Painting.all
  end
  def new
    @painting=Painting.new
  end
  def show
    @painting=Painting.find(params[:id])
  end
  def create
    #byebug
    @painting=Painting.new(painting_params)
    if @painting.save
  flash[:success]="Created image in album"
  redirect_to gallery_path(@painting)
else
  flash[:error]="Fail!"
  render 'new'
end
  end

  private
  def painting_params
    params.require(:painting).permit(:name,:gallery_id)
  end
end

图库控制器

class GalleriesController < ApplicationController
  def index
@galleries=Gallery.all
  end

  def new
@gallery=Gallery.new
  end

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

  def create
@gallery=Gallery.create!(gallery_params)
redirect_to galleries_path
  end

  private
  def gallery_params
      params.require(:gallery).permit(:name)
    end
end

确定2个模型文件: 的 gallery.rb

class Gallery < ApplicationRecord
  has_many :paintings
end

painting.rb

class Painting < ApplicationRecord
  def access_params
      params.require(:painting).permit(:gallery_id, :name, :image)
    end

 belongs_to :gallery, optional: true
 mount_uploader :image, ImageUploader
end

似乎一切顺利,但后来我坚持在画廊中的show.html.erb上显示图像的步骤。 的 show.html.erb

<div id="paintings">
  <% @gallery.paintings.each do |painting| %>
    <div class="painting">
      <%= image_tag painting.image_url.to_s %>
      <div class="name"><%= painting.name %></div>
      <div class="actions">
        <%= link_to "edit", edit_painting_path(painting) %> |
        <%= link_to "remove", painting, :confirm => 'Are you sure?', :method => :delete %>
      </div>
    </div>
  <% end %>
  <div class="clear"></div>
</div>

图像没有出现,但画廊的控制器中的闪光报告我创建了图像,我检查了网站然后我尝试在show.html.erb上打印绘画s'attributes

<%= @gallery.name %>
<%= @gallery.paintings.name %>
<%= @gallery.paintings.gallery_id%>
<%= @gallery.paintings.image%>

仅打印出画廊的名称和绘画名称。其他两种方法都有错误发生。

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

我不知道为什么画廊只能访问绘画的名字而不能访问其他两个。我搜索了这个错误,但我不认为这些情况适用于我的。男人们有什么问题?

2 个答案:

答案 0 :(得分:0)

您的“绘画”是一个集合,而不是单个图像,因此您需要对每个图像进行迭代或选择第一个:

<%= @gallery.paintings.first.name %>
<%= @gallery.paintings.first.gallery_id %>
<%= @gallery.paintings.first.image %>

答案 1 :(得分:0)

我发现了我的错误!在用户控制器中添加:image to method painting_params

def painting_params
    params.require(:painting).permit(:name,:gallery_id,:image)
  end