0

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
1
  • Can I point out this seems to be unexpected behavior? If I've gone to /homepage/5 and that's my store, if I accidentally go to /homepage I'll lose access to my store. What are you trying to accomplish here? Commented Jun 15, 2012 at 14:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

There are some errors when I apply your suggestions. Line 14 is : @user.update_attributes(:store => "0") [code]undefined method update_attributes' for nil:NilClass app/controllers/users_controller.rb:14:in access'[/code]
Ok, that means that current_user is not being set correctly. Or do you have a typo -- update_attributes' vs update_attributes
def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end
I added a store column to User table using SQlite manager, and change the model file and added :store to it. Are there any other changes needed in this process?
Re: current_user. You need to see if the code is working or not. It looks good but maybe something is wrong with the session. Re: adding a new column--did you add :store to the attr_accessible call in the User model file?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.