0

Deviseの編集ページに、クリップを使った画像アップローダーを配置しています。
ここに image_tag を入れようとすると、このようにエラーが返されます。

NoMethodError in Registrations#edit 
undefined method `photo' for #<ActionView::Helpers::FormBuilder:0x000000210752d0>

Deviseで使用される「ユーザー」モデルがあります。
User には 1 つの「UserProfile」モデルがあります。
「UserProfile」で、attr_accessible に :photo を追加しました。ペーパークリップを使用するために、これを「UserProfile」モデルにも追加しました

  has_attached_file :photo,
    :styles => {
    :thumb=> "100x100>",
    :small  => "400x400>" } 

私の編集ビューは

<% resource.build_user_profile if resource.user_profile.nil? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
  <%= devise_error_messages! %>

    <%= f.fields_for :user_profile do |profile_form| %>

      <div><%= profile_form.label :nickname %><br /> 
      <%= profile_form.text_field :nickname %></div> 

      <div><%= profile_form.label :photo %><br /> 
      <%= profile_form.file_field :photo %></div>

     <% if profile_form.photo.exists? then %>
      <%= image_tag profile_form.photo.url %>
      <%= image_tag profile_form.photo.url(:thumb) %>
      <%= image_tag profile_form.photo.url(:small) %>
     <% end %>
   <% end %> 

...continue on
4

2 に答える 2

0

新しく構築された user_profile を実際に変数に割り当ててみてください。

<% user_profile = resource.build_user_profile if resource.user_profile.nil? %>

次に、その変数を fields_for に次のように渡します。

<%= f.fields_for user_profile do |profile_form| %>

また

<%= f.fields_for :user_profile, user_profile do |profile_form| %>

私はそれがうまくいくと信じていますか?

于 2012-07-19T14:06:06.733 に答える
0

ネストされたフォームを作成するには、親モデル (ユーザー) でこれを追加します

accepts_nested_attributes_for :photos

これにより、Photo モデルとユーザーに関連するパラメーターを一度に渡すことができます。Rails は、 photo model の値を name という名前で格納する特別なハッシュ キーを作成します。

photos_attributes

これで、@user = User.new params[:user] を実行すると、@user.photos も構築されます

また、ユーザーコントローラーの新しいメソッドに、次を追加します: @user.photo.build

完全な説明については、ryan bates によるこの素晴らしい Railscast を参照してください: http://railscasts.com/episodes/134-paperclip

また、これも役立つかもしれません: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

于 2012-08-05T17:17:07.497 に答える