Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is update method for Rails Associations?

This is so simple that it's ridiculous I couldn't find any information about this anywhere including API docs and Rails source code:

I have a :belongs_to association and I've come to understand the normal model methods you call in the controller when you DON'T have an association are slightly different than the ones when you DO.

For example, I've got my association working fine for the create controller action:

@user = current_user
@building = Building.new(params[:building])

respond_to do |format|
   if @user.buildings.create(params[:building])
# et cetera

but I can't find docs on how update works:

@user = current_user
@building = @user.buildings.find(params[:id])

respond_to do |format|
  if @user.buildings.update(params[:building])
# et cetera

Using the update method gives the error "wrong number of arguments (1 for 2)" and I can't figure out what arguments are supposed to be sent.

like image 234
user478798 Avatar asked Dec 05 '10 08:12

user478798


People also ask

What is the difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.

What is ORM in ROR?

1.2 Object Relational Mapping Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

Use update_attributes:

@user = current_user
@building = @user.buildings.find(params[:id])

respond_to do |format|
  if @building.update_attributes(params[:building])
     #...
  end
end
like image 117
Jacob Relkin Avatar answered Oct 23 '22 17:10

Jacob Relkin