Inserting data to another DB table

I have a form under one controller/model called “billing” using the
“bills” table. When this form completes I want it to change the
“has_billing” field for the user under the “users” table from “0” to
“1”. I’ve almost got it. I put:

user = User.new
user.update_attribute(“has_billing”, “1”)

under the “create” function for the billing form. It creates a new user
in the “users” table and does apply “1” to the “has_billing” field.

How can I get it to change the field under the user submitting the form?
I have the session data saved under the “@session” variable and can
access it using “@session[‘user’].id”

how about

@session[‘user’].has_billing = 1
@session[‘user’].save

if that doesnt work , you can go the longer way round

@user = @session[‘user’]
@user.has_billing = 1
@user.save

or if that doesnt work you can go even longer
@user = User.find(@session[‘user’].id)
@user.has_billing = 1
@user.save

but i think the first should work…

d.

David Andersen wrote:

how about

@session[‘user’].has_billing = 1
@session[‘user’].save

if that doesnt work , you can go the longer way round

@user = @session[‘user’]
@user.has_billing = 1
@user.save

or if that doesnt work you can go even longer
@user = User.find(@session[‘user’].id)
@user.has_billing = 1
@user.save

but i think the first should work…

A couple coding style tips:

Say don’t use the @session inst var, instead use the session
accessor. It’s better to use the API than dig into inst vars even if you
can.

Don’t store the user object in the session. Instead you should store the
user_id in the session and grab the user object from the db when you
need it. You’ll avoid any number of synchronization and serialization
issues. And in general symbols are better than strings for hash keys,
since they compare by object id instead of by string contents.

if user = User.find_by_id(session[:user_id])
user.has_billing = 1
user.save
end

find_by_id is a nice way to find a model object because it returns nil
if there isn’t one for that id.


Josh S.
http://blog.hasmanythrough.com

None of David’s solutions worked for me. But I did end up using a
combination of my and David’s code. The line I had wrong was:

user = User.new

Once I used David’s suggestion to assign the id from the @session
variable to it’s own variable:

@user = User.find(@session[‘user’].id)

Then I used my call to change the attribute using the new variable:

@user.update_attribute(“has_billing”, “1”)

So, the whole thing goes:

def create
@bill = Bill.new(params[:bill])
@bill.user_id = @session[‘user’].id
@user = User.find(@session[‘user’].id)
@user.update_attribute(“has_billing”, “1”)
…more code…

Thanks guys