【问题标题】:Rails 4 Polymorphic Image uploads with Paperclip not working for all models使用 Paperclip 上传 Rails 4 多态图像不适用于所有模型
【发布时间】:2014-12-19 19:18:01
【问题描述】:

Rails 新手在这里......而且是第一次来......

经过几个教程后,我决定尝试构建一个事件管理系统。没有野心,对吧?活动、艺术家和公司都应该能够使用回形针和嵌套表单上传单个图像。我制作了一个多态图片类,它非常适合为艺术家上传/编辑图片,但是当我尝试使用完全相同的代码为事件设置它时,我得到一个“未经许可的参数:图片属性”错误...并且没有任何东西保存到数据库中。

过去 3 天我一直在搜索/阅读答案,但我完全陷入困境,所以我想我会把我的代码放在这里,看看是否有人能发现我可能遗漏的内容并帮助我弄清楚如何让它工作。

这是我上次尝试将图像上传到事件的实际错误代码:

Started PATCH "/events/12" for 127.0.0.1 at 2014-12-19 11:00:37 -0800
Processing by EventsController#update as HTML
Parameters: {"utf8"=>"✓",
 "authenticity_token"=>"AVkztH4s+t2oq/vjXloZeWxOW3pyD8sEorE3crMZr4Q=",
 "event"=>{"title"=>"Image Upload Test", "description"=>"Will this save to the db?",
 "picture_attributes"=>{
   "image"=>#<ActionDispatch::Http::UploadedFile:0x007fe7e9f6a3c8 @tempfile=#<Tempfile:/var/folders/kg/_bhw0x954nq1vdxsr4bwktvc0000gn/T/RackMultipart20141219-868-c377uk>, 
   @original_filename="RED_Tails_1.jpg", 
   @content_type="image/jpeg", 
   @headers="Content-Disposition: form-data; 
    name=\"event[picture_attributes][image]\"; 
    filename=\"RED_Tails_1.jpg\"\r\nContent-Type: image/jpeg\r\n">}, 
    "company_id"=>"1", 
    "venue_id"=>"1", 
    "production_artists_attributes"=>{
     "0"=>{"artist_id"=>"1", 
        "role"=>"German Commander", 
        "_destroy"=>"false", 
        "artist_type_id"=>"1", "id"=>"20"}}}, "button"=>"", "id"=>"12"}
Event Load (0.2ms)  SELECT  "events".* FROM "events"  WHERE "events"."id" = $1 LIMIT 1  [["id", 12]]
Unpermitted parameters: picture_attributes
(0.2ms)  BEGIN
ProductionArtist Load (0.2ms)  SELECT "production_artists".* FROM "production_artists"  WHERE
"production_artists"."event_id" = $1 AND "production_artists"."id" IN (20)  [["event_id", 12]]
SQL (1.3ms)  UPDATE "events" SET "company_id" = $1, "description" = $2, "title" = $3, "updated_at" = $4, "venue_id" = $5 WHERE "events"."id" = 12  [["company_id", 1], ["description", "Will this save to the db?"], ["title", "Image Upload Test"], ["updated_at", "2014-12-19 19:00:37.057793"], ["venue_id", 1]]
SQL (1.3ms)  UPDATE "production_artists" SET "artist_id" = $1, "role" = $2, "updated_at" = $3 WHERE "production_artists"."id" = 20  [["artist_id", 1], ["role", "German Commander"], ["updated_at", "2014-12-19 19:00:37.065119"]]
(90.1ms)  COMMIT
Redirected to http://localhost:3000/events/12
Completed 302 Found in 114ms (ActiveRecord: 93.3ms)

这是我的模型:

class Event < ActiveRecord::Base
  has_one :picture, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :picture
end

class Artist < ActiveRecord::Base   
  has_one :picture, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :picture
end

class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
  has_attached_file :image, :styles => { :small => "180x180#", :thumb => "60x60#" }, 
                        path: ":rails_root/public/system/:attachment/:id/:style/:filename",
                        url: "/system/:attachment/:id/:style/:filename"
  validates_attachment  :image, :presence => true,
                    :content_type => { :content_type => %w(image/jpeg image/jpg image/png) },
                    :size => { :in => 0..1.megabytes }
end

这是我的控制器:

class ArtistsController < ApplicationController
before_action :set_artist, only: [:show, :edit, :update, :destroy]

def index
 @artists = Artist.all
end

def show
end

def new
 @artist = Artist.new
 @artist.build_picture
end

def edit
end

def create
 @artist = Artist.new(artist_params)

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

def update
 respond_to do |format|
  if @artist.update(artist_params)
    format.html { redirect_to @artist, notice: 'Artist was successfully updated.' }
    format.json { render :show, status: :ok, location: @artist }
  else
    format.html { render :edit }
    format.json { render json: @artist.errors, status: :unprocessable_entity }
  end
 end
end

private
 def set_artist
  @artist = Artist.find(params[:id])
 end

 def artist_params
  params.require(:artist).permit(:first_name, :last_name,
    picture_attributes: [:image])
 end
end


class EventsController < ApplicationController
before_action :set_event, only: [:show, :edit, :update, :destroy]

def index
 @events = Event.all
end

def show
end

def new
 @event = Event.new
 @event.build_venue
 @venue = @event.build_venue
 @event.build_picture

end

def edit  
end

def create
 @event = Event.new(event_params)

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

def update
respond_to do |format|
  if @event.update(event_params)
    format.html { redirect_to @event, notice: 'Event was successfully updated.' }
    format.json { render :show, status: :ok, location: @event }
  else
    format.html { render :edit }
    format.json { render json: @event.errors, status: :unprocessable_entity }
  end
 end
end

def destroy
 @event.destroy
  respond_to do |format|
   format.html { redirect_to events_url, notice: 'Event was successfully destroyed.' }
   format.json { head :no_content }
 end
end

private
 def set_event
  @event = Event.find(params[:id])
 end

 def event_params
  params.require(:event).permit(:title, :description, :image_url, :company_id, :venue_id,
    production_artists_attributes: [ :id, :event_id, :artist_id, :artist_type_id, :role, :_destroy,
      venues_attributes: [ :id, :name,
        picture_attributes: [:image]]] )
 end
end

这是我的观点:

The Events form:
<%= form_for @event, html: { multipart: true } do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
<fieldset id="event-meta">
  <div class="form-group">
    <%= f.label :title %>
    <%= f.text_field :title, class: "form-control" %>
  </div>
  <div class="form-group">     
    <%= f.label :description %>
    <%= f.text_area :description, rows: 8, class: "form-control" %>
    <br />
  </div>
</fieldset>
<div class="form-group">
<p>Upload Picture</p>
  <%= f.fields_for :picture do |image_upload| %> 
    <%= image_upload.file_field :image, class: "form-control"  %>
  <% end %>
</div>
....

The Artist form:
<%= form_for @artist, html: { multipart: true } do |f| %>
   <%= render 'shared/error_messages', object: f.object %>
<div class="form-group">
   <%= f.label :first_name %>
   <%= f.text_field :first_name, class: "form-control"  %>
</div>
<div class="form-group">
   <%= f.label :last_name %>
   <%= f.text_field :last_name, class: "form-control"  %>
 </div>
<div class="form-group">
<p>Upload Picture</p>
  <%= f.fields_for :picture do |image_upload| %> 
    <%= image_upload.file_field :image, class: "form-control"  %>
  <% end %>
</div>

所以...在我看来,一切都应该有效...但事实并非如此。我可能遗漏了一些简单的东西,希望有人可以为我指出。

FWIW...昨晚在寻找答案时,我想创建一个多态 Profile 模型并将所有图像附加到具有 has_one 关系的图像可能会更好,但即使是这种情况...我会真的很想得到一些帮助,弄清楚为什么我现在不能让它工作,这样我就可以了解未来要寻找什么。我完全迷惑了。

【问题讨论】:

    标签: ruby-on-rails-4 paperclip polymorphic-associations strong-parameters


    【解决方案1】:

    经过数周的头撞墙……我解决了……但我觉得自己像个白痴。我把它留给遇到这个问题的其他人。

    原来我不太了解嵌套强参数的语法。通过在图片之前关闭制作艺术家和场地的嵌套属性,我能够让它工作。我也让它适用于公司模型。

    所以我改变了这个:

    def event_params
     params.require(:event).permit(:title, :description, :image_url, :company_id, :venue_id,
      production_artists_attributes: [ :id, :event_id, :artist_id, :artist_type_id, :role, :_destroy,
      venues_attributes: [ :id, :name,
        picture_attributes: [:image]]] )
    end 
    

    到这里:

    def event_params
     params.require(:event).permit(:title, :description, :image_url, :company_id, :venue_id,
      production_artists_attributes: [:id, :event_id, :artist_id, :artist_type_id, :role, :_destroy],
       venues_attributes: [:id, :name],
        picture_attributes: [:image])
    end
    

    一切都像魅力一样。

    【讨论】:

      【解决方案2】:

      尝试将event_params 方法更新为:

      def event_params
        params.require(:event).permit(:title, :description, :image_url, :company_id, :venue_id,
        production_artists_attributes: [ :id, :event_id, :artist_id, :artist_type_id, :role,    :_destroy,
         venues_attributes: [ :id, :name,
          imageable_attributes: [:image]]] )
      end
      

      这里的事情是您将has_one 关系的as 选项设置为imageable,并且您可能必须对模型字段中的视图执行类似的操作:

      accepts_nested_attributes_for :imageable
      
      <%= f.fields_for :imageable do |image_upload| %> 
        <%= image_upload.file_field :image, class: "form-control"  %>
      <% end %>
      

      告诉我进展如何。

      【讨论】:

      • 感谢您的回复。试过这个。现在我收到“Unpermitted parameters: imageable”错误消息,db 也看不到任何东西。
      • 您是否在event_params 方法中为 imageable_attributes 添加了正确的名称?
      • 是的,我确实做出了改变。我真的很茫然。
      • 我确实重启了服务器,但还是不行。我只是在学习如何使用控制台,所以我并没有真正使用它,没有。
      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 2015-03-10
      • 2016-07-30
      • 2014-01-18
      • 2014-10-16
      • 2011-01-14
      相关资源
      最近更新 更多