<%= f.label :title %>
<%= f.text...">

Rails 3 - pass user.id to a hidden form field using association

Ok so now 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 current_user.id to the create method of my "app" model, which creates it like this before saving it:

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

However, I have associations (pseudo-code)

 user has_many apps apps belongs_to user 

Question: is it safer (so the form does not change) to do something similar in the creation method?

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

If so ... how exactly will I be implementing the code above (its not syntactically correct .. just pseudo)?

Thanks!

+6
source share
3 answers

Yes, using the second method that you suggested is the best approach

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

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

+9
source

It is absolutely safe to do this in a second way. If you do this the first way, you trust the client to indicate who they are. Anyone can easily change the form (using firebug, or they could manually send a POST request with many tools) and end up sending the form using current_user another person.

Make sure you apply this thinking throughout the application. Do not trust what the client serves, ever.

+4
source

The second code snippet is more "RESTful" than the first. The more RESTful, I mean, if the application is a resource that is logically accessible through the user, then by all means, use it.

The way you set this along the 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 the user ID, application ID, or new application.

Hope this helps

+1
source

Source: https://habr.com/ru/post/888064/


All Articles