Rails 3 -- Pass user.id in hidden form field vs using association
Asked Answered
W

3

6

Ok so currently I have a form

<div class="field">
  <%= f.label :title %><br/>
  <%= f.text_field :title %><br/>
  <%= f.label :itunesurl %><br />
  <%= f.text_field :itunesurl %><br />
  <%= f.hidden_field :user_id, :value => current_user.id %>
</div>
<div class="actions">
  <%= f.submit %>
</div>

Which passes the current_user.id into the create method of my "app" model which creates it like this before saving it:

@app = App.new(params[:app])

However I have associations of (pseudocode)

user has_many apps
apps belongs_to user

Question: is it safer (so the form doesn't get modified) to do something like this within the create method?

@user = current_user
@app = @user.apps.create(params[:app])

If so... how exactly would I go about actually implementing the code above (its not syntactically correct.. just pseudo)?

Thanks!

Whitmore answered 13/5, 2011 at 18:45 Comment(0)
T
10

Yes using the second way that you have suggested is the best approach

@user = current_user
@app = @user.apps.create(params[:app])

Also make sure you protect yourself from mass assignment, take a read of this http://stephensclafani.com/2010/01/04/ruby-on-rails-secure-mass-assignment/

Thorner answered 13/5, 2011 at 18:57 Comment(0)
R
5

It's absolutely safer to do it the second way. If you do it the first way, you're trusting the client to state who they are. Anyone could easily modify the form (with firebug, or they could manually submit a POST request with many tools) and end up submitting a form with the current_user of another person.

Make sure you apply this thinking everywhere throughout your app. Do not trust anything the client submits, ever.

Rockie answered 13/5, 2011 at 18:53 Comment(0)
R
1

The second code snippet is more "RESTful" than the first. By more RESTful, I mean, if an App is a resource that is logically accessed through a User, then by all means use it.

The way you set that up through routes:

resources :users do
  resources :apps
end

This will give you paths like user_app_path and new_user_app_path, to which you pass a user ID and an app ID or a new app.

Hope this helps

Revolution answered 13/5, 2011 at 18:49 Comment(2)
Thats rails 2 syntax. Since the question addresses rails 3 in the tags I'll fix it for you (feel free to roll back if undesired)]Karakalpak
I kinda knew it was a rails 2 syntax and was too lazy/in a hurry, to look up the rails 3 version of it. Thanks for the edit, :)Revolution

© 2022 - 2024 — McMap. All rights reserved.