【问题标题】:How to use the gem 'paperclip' with nested form如何使用嵌套形式的宝石“回形针”
【发布时间】:2023-03-17 14:46:01
【问题描述】:

在 Devise 的编辑页面中,我使用回形针放置图像上传器。
如果我尝试将 image_tag 放在这里,它会像这样返回错误。

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

我有 Devise 使用的“用户”模型。
并且用户有一个“用户配置文件”模型。
在“UserProfile”中,我将 :photo 添加到 attr_accessible。 为了使用回形针,我还将它添加到“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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations paperclip nested-forms


    【解决方案1】:

    尝试将新建的 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| %>
    

    我相信这应该有效?

    【讨论】:

      【解决方案2】:

      要制作嵌套表单,请在您的父模型(用户)中添加此

      accepts_nested_attributes_for :photos
      

      这允许您一次性传递与照片模型和用户相关的参数。 Rails 制作了一个特殊的哈希键,用于存储带有名称的照片模型的值:

      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-12-25
        • 2012-04-07
        • 1970-01-01
        • 1970-01-01
        • 2014-04-13
        • 1970-01-01
        • 2019-09-24
        • 2015-09-08
        • 1970-01-01
        相关资源
        最近更新 更多