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!
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With