私はフォームを持っています:
<%= form_for [:admin, @category], :html => { :multipart => true } do |f| %>
<%= f.collection_select(:parent_id, Category.all, :id, :title, include_blank: true) %><br />
<%= f.label :title %><br />
<%= f.text_field :title %><br />
<%= f.label :description %><br />
<%= f.text_area :description %><br />
<%= fields_for :category_image do |category_image_fields| %>
<%= category_image_fields.file_field :attachment %><br />
<% end %>
<%= f.submit %>
<% end %>
しかし、それをフリーズして、better_errors gem を使用して試してみると、うまくいかないようです:
>> params
=> {"utf8"=>"✓", "authenticity_token"=>"JWT+P6OQHKQC+sx5ytNoyAaGEKwCHb15Mb0H7FSJlTM=", "category"=>{"parent_id"=>"3", "title"=>"ffff", "description"=>"ffff"}, "category_image"=>{"attachment"=>#<ActionDispatch::Http::UploadedFile:0x007fdd375e9590 @original_filename="bacon.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"category_image[attachment]\"; filename=\"bacon.jpg\"\r\nContent-Type: image/jpeg\r\n", @tempfile=#<File:/var/folders/nw/zzv_cpt94_18vhvmcwk26gh80000gr/T/RackMultipart20131017-37289-1k42gos>>}, "commit"=>"Create Category", "action"=>"create", "controller"=>"admin/categories"}
>> c=Category.new(params[:category])
=> #<Category id: nil, title: "ffff", description: "ffff", parent_id: 3, created_at: nil, updated_at: nil>
>> c.category_image
=> nil
これは、画像を表すペーパークリップを使用する私のモデルです。
class CategoryImage < Asset #<-- trying to reuse it for other models too
belongs_to :category
end
class Asset < ActiveRecord::Base
has_attached_file :attachment
validates_attachment_presence :attachment
validates_attachment_content_type :attachment,
:message => "Please upload correct format",
:content_type => %w( image/jpeg image/png image/pjpeg image/x-png image/gif)
has_attached_file :attachment, :styles => { :small => '100' }
attr_accessible :attachment
end
has_one
これは、イメージする必要がある私のカテゴリ モデルです。
class Category < ActiveRecord::Base
attr_accessible :title, :description, :category_image, :parent_id
has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy
belongs_to :parent_category, class_name: 'Category', foreign_key: 'parent_id'
has_many :books
has_one :category_image
accepts_nested_attributes_for :category_image
validates_presence_of :title, :description
end