Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 688
Msencenb Avatar asked May 13 '11 18:05

Msencenb


2 Answers

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/

like image 53
Scott Avatar answered Sep 20 '22 01:09

Scott


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.

like image 34
ryeguy Avatar answered Sep 19 '22 01:09

ryeguy