【发布时间】:2014-10-25 21:08:04
【问题描述】:
我有一个用户模型,其中包含三个与之关联的附加模型:City、State、Country。它们的关联如下:
class User < ActiveRecord::Base
has_one :city
has_one :state
has_one :country
end
class City < ActiveRecord::Base
belongs_to :state
belongs_to :user
end
class State < ActiveRecord::Base
has_many :cities
belongs_to :country
belongs_to :user
end
class Country < ActiveRecord::Base
has_many :states
belongs_to :user
end
我想做的是创建一个表单,允许新/现有用户将此类信息添加到他们的个人资料中。但是在 Rails 控制台中尝试了这个之后,我发现要完成这些事情变得很重。
city = City.create(name: "New York City")
city.state = state
state = State.create(name: "New York")
state.country = country
country = Country.create(name: "United States")
user = User.create(name: "John Doe")
user.city = City.first
user.state = user.city.state
user.country = user.state.country
我的最终目标是能够使用自动完成功能创建选择框或输入,以便能够检索和返回所选内容的数据。因此,如果我在 City 的选择框中选择 New York City,那么 State 选择框将返回 New York(父子配对)。有没有更好的方法将这些模型相互分配?
奖励积分:用于显示控制器逻辑。当我继续认为那里的事情很可能会出现用户进入网站上不可用的新州、城市或国家的时候。我假设我的用户控制器的创建/更新看起来像这样,但就其他剩余操作而言,我似乎想不出解决方案?
# users_controller.rb
def create
@user.build_city
@user.build_state
@user.build_country
end
【问题讨论】:
标签: ruby-on-rails ruby activerecord model associations