Yagiz
Yagiz

Reputation: 1033

ruby on rails changing variable

i have a problem in ruby on rails. I want to make current user's store id to be 0 when user accesses to /homepage/, and i want to make user's store id to be the input id in the url when user accesses to /homepage/:id/.

My code:

routes.rb:
  match "/homepage" => "users#access", :as => "store"
  match "/homepage/:id" => "users#homepage", :as => "store"

def access
  @user = current_user
  @user.update_attributes(:store => "0")
  @user.save
end

def homepagestore
  @user = current_user
  @user.update_attribute(:id, user.store = :id)
  @user.save
end

Upvotes: 0

Views: 116

Answers (1)

Larry K
Larry K

Reputation: 49114

update_attribute updates the record in the database. But it skips the validation checks. update_attributes also updates (saves) the record in the database. It does not skip validation.

So:

  1. You should use params[:id] as Sergio says
  2. You may want to use update_attributes instead since it does not skip validation checks
  3. You do NOT need the save method if you use update_attribute or update_attributes

My suggestions:

def access
  @user = current_user
  @user.update_attributes(:store => "0")
end

def homepagestore
  @user = current_user
  @user.update_attributes(:store => params[:id])
end

Added update_attributes uses the mass-assignment protection system. So you need the :store field in your User model's attr_accessible call to allow it to be changed. Or override the protection, see the update_attributes docs. Ask if you have more questions.

Upvotes: 2

Related Questions