Ruby on rails 嵌套形式:创建与两个同样相关的对象相关的对象
更新:我做了一些有效的事情,我会写下来作为我自己对这个问题的答案。但是它绕过了guide_params函数,所以我认为它不安全。如果有人能找到更好的方法,我将不胜感激 我有三个目标。父对象是Guide,我有一个嵌套的表单来创建它。本指南属于城市北京和国家东京。这两种模式有许多指导 我能够使用accepts_nested_attributes_正确初始化Guide CityObj和Guide CountryObj关系 问题在于CityObj和CountryObj是相互关联的。CityObj属于CountryObj,CountryObj拥有许多CityObj。我不知道在创建指南时如何初始化CityObj-CountryObj关系 此外,CountryObj.name是唯一的(只有一个法国),CityObj.name/CountryObj.id是唯一的(只有一个法国巴黎,但也有一个美国巴黎)。但我不想使用验证来阻止在现有城市/国家/地区创建指南。法国巴黎应该有很多导游。因此,我必须能够处理控制器中的重复项Ruby on rails 嵌套形式:创建与两个同样相关的对象相关的对象,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,更新:我做了一些有效的事情,我会写下来作为我自己对这个问题的答案。但是它绕过了guide_params函数,所以我认为它不安全。如果有人能找到更好的方法,我将不胜感激 我有三个目标。父对象是Guide,我有一个嵌套的表单来创建它。本指南属于城市北京和国家东京。这两种模式有许多指导 我能够使用accepts_nested_attributes_正确初始化Guide CityObj和Guide CountryObj关系 问题在于CityObj和CountryObj是相互关联的。CityObj属于Co
def create
@guide = current_user.build_guide(guide_params)
set_city_country
if @guide.save
...
end
Guide.rb
class Guide < ActiveRecord::Base
belongs_to :city_obj
belongs_to :country_obj
accepts_nested_attributes_for :city_obj, :country_obj
end
我的创建函数调用
@guide = current_user.build_guide(guide_params)
那就
@guide.city_obj = <a city object>
@guide.country_obj = <a country object>
@guide.country_obj.city_obj = nil
@guide.city\u obj=
@guide.country_obj=
@guide.country\u obj.city\u obj=nil
如何设置最终关系?我认为这不安全,因为它绕过了限制所需参数的guide_params方法 为了实现这一点,我在控制器中手动设置coutnry_obj和city_obj
def create
@guide = current_user.build_guide(guide_params)
set_city_country
if @guide.save
...
end
我使用set_city_country功能创建和更新:
def set_city_country
# Building guide with guide_params is not setting city_obj.country_obj.
# Also need to manaually ensure city_obj/country_obj and country_obj are unique
country = params[:guide][:country_obj_attributes][:name]
city = params[:guide][:city_obj_attributes][:name]
@guide.country_obj = CountryObj.find_or_create_by(name: country)
@guide.city_obj = CityObj.find_or_create_by(name: city,
country_obj_id: @guide.country_obj.id)
@guide.city_obj.country_obj = @guide.country_obj
end
def create
@guide = current_user.build_guide(guide_params)
set_city_country
if @guide.save
...
end
def set_city_country
# Building guide with guide_params is not setting city_obj.country_obj.
# Also need to manaually ensure city_obj/country_obj and country_obj are unique
country = params[:guide][:country_obj_attributes][:name]
city = params[:guide][:city_obj_attributes][:name]
@guide.country_obj = CountryObj.find_or_create_by(name: country)
@guide.city_obj = CityObj.find_or_create_by(name: city,
country_obj_id: @guide.country_obj.id)
@guide.city_obj.country_obj = @guide.country_obj
end