开发者

In Rails, how do you swap a new object for an existing one?

开发者 https://www.devze.com 2023-03-09 07:14 出处:网络
I have the following nested model relationship: Countries (id, name) Provinces (id, country_id, name) Cities (id, province_id, name)

I have the following nested model relationship:

  • Countries (id, name)
    • Provinces (id, country_id, name)
      • Cities (id, province_id, name)

I have validates_uniqueness_of constraint on the name fields for each model in the relationship and a unique index on the name columns in the database.

I want to swap a new object created with the same name as an existing record at some point before it's validated. In other words, if a user attempts to add a city, province, country combination that has already been added, I want to country model to return a reference to the corresponding existing model records instead of failing validation before save.

I'm having trouble using the model callbacks (after_initialize开发者_运维百科, before_validation, etc.) and I wasn't able to get Country.find_or_initialize_by_name to work with the nested models... any suggestions?


What you are trying to do sounds pretty hard and will probably require you to know a lot of the internal implementation details of ActiveRecord::Base.

Instead, could you do something like this?

@country = Country.find_or_initialize_by_name(params[:name])
...
@country.save

EDIT: ActiveRecord has find_or_create_by_XXX and find_or_initialize_by_XXX functions built in, so there is no need to add a function to the model. For more info see the "Dynamic attribute-based finders" section of http://api.rubyonrails.org/classes/ActiveRecord/Base.html

0

精彩评论

暂无评论...
验证码 换一张
取 消