2

레일 초보자 여기에 모든 모델에 대해 작동하지 않습니다와 업로드 ... 그래서 첫 번째 타이머 .... 내가 시도하고 이벤트 관리 시스템을 구축하기로 결정 몇 자습서 후레일 4 개 다형성 이미지 종이 클립이

. 야망 같은 건 없지, 그렇지? 이벤트, 아티스트 및 회사는 모두 Paperclip 및 중첩 된 양식을 사용하여 단일 이미지를 업로드 할 수 있어야합니다. 다형성 그림 클래스를 만들었고 아티스트의 그림을 업로드/편집하는 데 적합하지만 동일한 코드를 사용하여 이벤트를 설정하려고하면 "Unpermitted parameter : picture_attributes"오류가 발생합니다. ... 아무것도 DB에 저장하지 않습니다.

나는 지난 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 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 
: 여기
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 

내 컨트롤러입니다

내 의견 :

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 ... 어젯밤에 답변을 검색하는 동안 다형성 프로필 모델을 만들고 has_one 관계가있는 이미지에 모든 이미지를 첨부하는 것이 더 좋을지도 모른다고 생각했지만, d는 왜 내가 지금이 일을 할 수 없는지를 알아내는 데 도움이되기 때문에 앞으로 어떻게 할 것인지 배울 수 있습니다. 나는 완전히 당혹 스럽다.

답변

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 

및 모든 마법처럼 일했다.

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 
여기에있는 것은 당신이 imageable 될하기 위해 has_one 관계에 대한 as 옵션을 설정하고, 아마 당신이보기에 대한 비슷한 일을해야 할 것입니다

모델의 필드 및 모델에서 :

accepts_nested_attributes_for :imageable 

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

어떻게되는지 알 수 있습니다.

+0

응답 해 주셔서 감사합니다. 이것을 시도했다. 이제 "Unpermitted parameters : imageable"오류 메시지가 표시되고 다시 DB에 표시되지 않습니다. – Jailyard90Grad

+0

'event_params' 메소드에 imageable_attributes에 올바른 이름을 추가 했습니까? – kurenn

+0

그래, 그 변화를 만들었 어. 나는 정말 실망 스럽다. – Jailyard90Grad

관련 문제