Monday, January 15, 2007

Rails Tip : Creating New Data (locked to the User)

(Update: Great post at the Rails Way site.)

This is a small continuation from yesterday's, "Access to Data", Rails Tip. (The biggest, "duh", tip ever. I promise, this one is a little less obvious!)

The code I used to illustrate constraining your find methods to the current user's account was this:

def show
@project = Project.find_by_id_and_account_id(params[:id], account_of_user().id)
end

You can do something similiar for creating new objects, by using associations.

def create
@project = account_of_user.projects.build(params[:project])
end

This binds the new project to the account of the user. ("account_of_user" being a reference to the account of the user you've authenticated.)

I can't believe I didn't know you could do this until I came across this post while researching Rails-related security.

Labels: ,

0 Comments:

Post a Comment

<< Home