使用Paperclip上传的Rails 4 Polymorphic Image不适用于所有型号

时间:2014-12-19 19:18:01

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

Rails新手在这里......并且是第一次......#/ p>

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

过去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关系的那些图像可能会更好,但即使这样也是如此。我真的很喜欢帮助弄清楚为什么我现在不能让它工作,所以我可以学习如何寻找未来。我完全不知所措。

2 个答案:

答案 0 :(得分: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

一切都像魅力一样。

答案 1 :(得分:0)

尝试将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

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

accepts_nested_attributes_for :imageable

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

让我知道它是怎么回事。