小编sim*_*aob的帖子

Ruby on Rails:嵌套属性,belongs_to关系

我有一个具有当前位置字段(城市和国家/地区)的用户实体.为了保存这些信息,我创建了一个名为Location的实体has_many Users.

我不完全确定我是否应该在用户模型中添加"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]) …
Run Code Online (Sandbox Code Playgroud)

attributes nested ruby-on-rails belongs-to

9
推荐指数
1
解决办法
1万
查看次数

标签 统计

attributes ×1

belongs-to ×1

nested ×1

ruby-on-rails ×1