2012-03-02 3 views
0

사용자의 사용자 계정과 연결된 여러 사진을 추가하는 기능을 추가하고 싶습니다.레일스 - 모델의 일부분만을위한 update_attributes; 파일 업로드

나는 다음과 같은 클래스가 :

class User < ActiveRecord::Base 
    has_many :assets 
    accepts_nested_attributes_for :assets 
end 

class Asset < ActiveRecord::Base 
    belongs_to :assetable, :polymorphic => true 
    belongs_to :user 
end 

난 그냥 업로드 이미지 기능이있는 화면을 갖고 싶어를 :

def add_profile_picture 
    @user=User.find(params[:id]) 
    1.times {@user.assets.build} 
end 

형태 : 내가 제출

<%= form_for @user do |u| %> 
    <%= u.fields_for :assets do |asset| %> 
    <%= asset.file_field :asset %> 
    <%= asset.text_field :description %><br /> 
    <% end %> 
    <%=u.submit %> 
<% end %> 

id 값이 development.log에서 ok로 표시됩니다.

"id"=>"1" 

하지만 오류 얻을 :

정의되지 않은 메서드`update_attributes '무기 호에 대한 : 난 그냥 자산 필드를 가지고 있기 때문에 NilClass

를, 내가해야 할 특별한 있나요? 또한, belongs_to : 사용자가 존재하기 때문에 문제가 발생할 수 있습니까? 기본적으로 :

아무 도움이됩니다. Rails 양식을 많이 사용하지 마십시오.

들으

편집 # 1

class UsersController < ApplicationController 
    def add_profile_picture 
    @user=User.find(params[:id]) 
    1.times {@user.assets.build} 
    end 

들으

+0

컨트롤러의 관련 작업 코드를 붙여 넣을 수 있습니까? –

+0

이 작업은 위의 작업에서 수행되었습니다. 응답은 thx – timpone

답변

0

좋아 - 여기에 코드와 몇 가지 문제가있다. 자세한 내용은 Action Controller OverviewRails Routing 가이드를 모두 읽어 보시기 바랍니다.

어쨌든 여기에있는 양식이 동작을 사용하려고하기 때문에 오류가 발생합니다 (UsersController).

몇 가지 옵션이 있습니다. 하나는 사용자 지정 작업에 필요한 경로를 만드는 것입니다. 또는 중첩 된 리소스를 만들고 자산을 추가하기위한 양식을 만들 수 있습니다. 의 AssetsController에, 그리고

resources :users do 
    resources :assets, :only => [:new, :create] # Or any other actions you might want. It's best practise to limit these. 
end 

routes.rb에서이 유사한 수행 할 수 있습니다 :이 경우

, 당신은 같은 것을 할 것

def new 
    @asset = Asset.new 
end 

def create 
    @asset = Asset.new(params[:asset]) 
    @asset.user_id = params[:user_id] if params[:user_id] 
    @asset.save! 
end 

을 양식이 다음과 같이 표시됩니다.

<%= form_for @asset do |f| %> 
    <%= f.file_field :asset %> 
    <%= f.text_field :description %><br /> 
    <%=f.submit %> 
<% end %> 
+0

입니다. 그래서 URL은 중첩 된 자원에 대해'/ users/1/assets/edit'이 될 것입니까? 또한, belongs_to와 다형 관계를 처리 할 수 ​​있습니까?thx again – timpone

+0

이것을 들여다 보니 사용자 # 업데이트를 사용하고 있다는 것을 알고 있습니다. 그것은 중첩 된 속성을 사용하여 의도 된 것입니다. id가 post'd 매개 변수에 전달되므로 작업해야하는 것처럼 보입니다. – timpone

관련 문제