我有一个具有当前位置字段(城市和国家)的用户实体。为了保存这些信息,我创建了一个名为 Location 的实体,该实体拥有多个用户。
我不完全确定是否应该放入用户模型“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