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

Msencenb picture Msencenb · May 13, 2011 · Viewed 11.1k times · Source

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!

Answer

Scott picture Scott · May 13, 2011

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/