Вопрос

when using find_or_create_by_name in rails, if the table is found and you pass in parameters for other attributes, will it update the table? for example:

College.find_or_create_by_name(name: 'University of Pittsburgh', calendar: 'semester')

Say the University of Pittsburgh table has already been created, but the calendar attribute is nil. Will this code update the calendar attribute to make it 'semester'?

Some context... I'm making a website with a bunch of pages for different colleges. Part of the website involves listing a bunch of data for the college. Right now I'm writing my seed file, but I anticipate having to change it. I'd like to have hundreds of schools on the website, and for each school, there are going to be hundreds of different pieces of data. I was thinking that having the seed file and using find_or_create_by_name would be a good way to do this, but if you have a better way, please let me know.

Это было полезно?

Решение 2

find_or_create_by_ does exactly what it says: it either creates a new item (create saves to database) or finds the existing one, meaning reads it from the database.
It returns false on validation errors when creating an object

So to save changes you use the normal update methods:

if @college= College.find_or_create_by_name(given_attributes) &&
   @college.update_attributes(given_attributes)
else
  # handle validation errors
end

It won't hit the database twice, because update_attributes does'n apply any changes to newly created objects (but possible changes to existing ones)

To write it more explicit:

@college= College.find_or_create_by_name(given_attributes)
if @college.present?
   if @college.update_attributes(given_attributes)
     # do your success stuff
   else
     # handle update validation errors
   end
else
  # handle find_or_create errors
end

Другие советы

That code won't update the record if it already exists. I would suggest:

@college = College.find_or_initialize_by_name("Robot House!!")
@college.attributes = {
  reputation: "partyhouse",
  occupants: "robots"
}
@college.save!

You could wrap this in a method if you needed to.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top