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.
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? 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.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
Use update_attributes
:
@user = current_user
@building = @user.buildings.find(params[:id])
respond_to do |format|
if @building.update_attributes(params[:building])
#...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With