そのため、フォームを介してドレス オブジェクトのプライマリ イメージを設定する際に問題が発生しています。フォームを使用すると、ユーザーはドレスの詳細を編集し、(nested_form を使用して) フォームに画像を追加/削除し、それぞれにラベルを設定してプライマリ画像を割り当てることができます。
これまでのところ、ラジオ ボタンを使用してプライマリ イメージを設定する以外はすべて機能しています。
ドレスモデル:
class Dress < ActiveRecord::Base
has_many :dress_images
has_one :primary_dress_image, :class_name => "DressImage", :conditions => { :is_primary => true }
accepts_nested_attributes_for :dress_images, :allow_destroy => true
validates :name, :presence => true, :length => { :maximum => 99 }
end
ドレスイメージモデル
class DressImage < ActiveRecord::Base
belongs_to :dress
# Same as:
# def self.primary
# where(:is_primary => true)
# end
scope :primary, where(:is_primary => true)
# clear old primary if:
# this is a new record
# this is existing and is_primary has been set to true
before_save :clear_primary,
:if => Proc.new{ |r| (r.new_record? && r.is_primary) || (r.is_primary_changed? && r.is_primary) }
validates :label, :presence => true, :length => { :maximum => 60 }
validates :caption, :length => { :maximum => 200 }
mount_uploader :image, ImageUploader
def clear_primary
DressImage.update_all( {:is_primary => false}, :dress_id => self.dress_id )
end
end
ドレス編集フォーム
<h1>Dress</h1>
<% @dress.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %> <%#= f.label :name %>
<%= nested_form_for @dress, :as => :dress, :url => { :action => :update }, :html=>{ :multipart => true } do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.fields_for :dress_images do |dress_image_form| %>
<div class="dress-image">
<%= image_tag dress_image_form.object.image_url(:thumb) %>
<%= dress_image_form.text_field :label %>
<%= dress_image_form.file_field :image %>
<div class="primary-image-radio">
<%= dress_image_form.label :is_primary, "Main Image" %>
<%= f.radio_button :primary_dress_image_id, dress_image_form.object.id %>
</div>
<p>
<%= dress_image_form.link_to_remove "Remove this attachment" %>
</p>
</div>
<% end %>
<%= f.link_to_add "Add Photo", :dress_images %>
<%= f.submit "Save Dress" %>
<% end %>
このラジオ ボタンでは、ドレス オブジェクトに primary_dress_image_id 属性が設定されますが、@dress.primary_dress_image は ID に異なる結果を与えます。
ラジオボタンを に変更する<%= dress_image_form.radio_button :is_primary, true %>
と動作が良くなりますが、各ラジオボタンの名前が異なるため、同じグループとして扱われません。
私はレールに慣れていないので、完全に明らかな何かを見逃しているか、すべて間違っている可能性があります。