Ruby on rails 用于将字符串转换为一对多关联的外键的方法
对于我访问过的地区,我有一个rails模型Ruby on rails 用于将字符串转换为一对多关联的外键的方法,ruby-on-rails,model-associations,Ruby On Rails,Model Associations,对于我访问过的地区,我有一个rails模型Region区域与位置模型有一对多关联,该模型包含我在该区域内访问过的特定位置 每个区域都有一个名称字符串列。我的路由设置为使用给定的区域.name来形成大多数URL-/:name/new\u location。这是出于美观的原因,因为我不想让一个数字(地区id)构成URL 因此,对于我添加到区域的每个新位置,都需要分配一个region\u id外键。现在,我通过在我的位置中有一个区域名称列来实现这一点。然后,我的new位置表单有一个字段“Region
Region
<代码>区域与位置
模型有一对多关联,该模型包含我在该区域内访问过的特定位置
每个区域都有一个名称
字符串列。我的路由设置为使用给定的区域.name
来形成大多数URL-/:name/new\u location
。这是出于美观的原因,因为我不想让一个数字(地区id)构成URL
因此,对于我添加到区域的每个新位置,都需要分配一个region\u id
外键。现在,我通过在我的位置中有一个区域名称
列来实现这一点。然后,我的new
位置表单有一个字段“Region name”,其中输入了一个字符串
要将新创建的位置
与其区域
实际关联,mylocations\u controller
中的创建
方法包含一段代码,如下所示:
# CONVERT REGION_NAME TO REGION_ID
location = Location.new
l = location.region_name.downcase
if l == "chicagoland"
location.region_id = 3
elsif l == "roadtrip 2016"
location.region_id = 4
#...
end
location.save
redirect_to("/regions/#{region.name}/#{location.id}")
因此,对于我创建的每个新的区域
,我无法添加新的位置,除非我手动将其字符串名称与其id
——通过向我的位置控制器
中的创建
方法添加新代码。因此,如果我创建了一个名为“阿尔冈金省级公园”的新区域,id=28,我需要更新我的位置\u控制器
-将阿尔冈金省级公园
连接到28
,并将位置.region\u id
设置为28
。这显然不是最优的
是否有办法对我的new
和create
方法进行编程,使新的位置
自动分配一个外键,该外键相当于它所属的区域
的区域id
,每次有新的区域时,无需向我的位置添加代码即可创建方法 作为一个介绍,您试图做的事情有时会提到or。你可以自己掷,也可以使用宝石。看起来你已经走上了自己的道路(我也是这么做的)。如果您的name
字段曾经包含非url友元元素,那么您可能需要研究使用slug
。我把它留给你自己研究
在您的routes.rb
中,假设您有:
resources :regions, param: :name do
resources :locations
end
class Region < ActiveRecord::Base
has_many :locations
end
这将给你:
region_locations GET /regions/:region_name/locations(.:format) locations#index
POST /regions/:region_name/locations(.:format) locations#create
new_region_location GET /regions/:region_name/locations/new(.:format) locations#new
edit_region_location GET /regions/:region_name/locations/:id/edit(.:format) locations#edit
region_location GET /regions/:region_name/locations/:id(.:format) locations#show
PATCH /regions/:region_name/locations/:id(.:format) locations#update
PUT /regions/:region_name/locations/:id(.:format) locations#update
DELETE /regions/:region_name/locations/:id(.:format) locations#destroy
regions GET /regions(.:format) regions#index
POST /regions(.:format) regions#create
new_region GET /regions/new(.:format) regions#new
edit_region GET /regions/:name/edit(.:format) regions#edit
region GET /regions/:name(.:format) regions#show
PATCH /regions/:name(.:format) regions#update
PUT /regions/:name(.:format) regions#update
DELETE /regions/:name(.:format) regions#destroy
我们还假设您有:
resources :regions, param: :name do
resources :locations
end
class Region < ActiveRecord::Base
has_many :locations
end