現在の場所フィールド (都市と国) を持つユーザー エンティティがあります。この情報を保持するために、ユーザー数が多い Location というエンティティを作成しました。
User モデルに「has_one」または「belongs_to」を入れる必要があるかどうかは完全にはわかりませんが、場所の外部キーを持たせたい場合は、「belongs_to」を入れる必要があります。また、ユーザーを編集するときにユーザーの現在の場所を編集できるようにしたいと考えています。そのため、ネストされた属性を使用しています。しかし、ユーザーを編集すると、編集されたユーザーに関連付けることなく、毎回新しい場所を追加することになります。あなたは私を助けることができます?
私のコードは次のとおりです。
#User Model
class User < ActiveRecord::Base
## Relationships
belongs_to :current_location, :class_name => 'Location'
accepts_nested_attributes_for :current_location
end
#Location Model
class Location < ActiveRecord::Base
#Relationship
has_many :users
end
# part of the _form_edit.haml
- form_edit.fields_for :current_location do |location_form|
= location_form.label :location, "Current Location"
= location_form.text_field :location
#Application Helper
#nested attributes for user and location
def setup_user(user)
returning(user) do |u|
u.build_current_location if u.current_location.nil?
end
end
#in the user controller (added after edit)
def update
@user = @current_user
if @user.update_attributes(params[:user])
flash[:notice] = "Account updated!"
redirect_to account_url
else
render :action => :edit
end
end