Rails 4 params validation -


user create post , assign 1 of collections (post belongs_to collection)

i have working dropdown read collection_id current user, however, i'd avoid user(attacker) pass wrong parameters collection_id belongs incorrect user.

i tested using text_field , assign collection_id incorrect user , post saved, want prevent.

how can that?

1) within business layer. (i guess inside model validation)

2) within db layer (some db constrains)

3) preferable both

note: need pre-fill form variables previous step, user can change or fill in case empty

post_controller.rb:

@post = current_user.posts.build(url: @url, content: @title)  def post_params   params.require(:post).permit(:content, :url, :collection_id) end 

models:

collection.rb: belongs_to :user has_many   :posts  user.rb: has_many :posts has_many :collections  post.rb: belongs_to :user belongs_to :collection 

routes:

post   'post'    => 'posts#create' 

form:

<%= form_for(@post, html: { multipart: true }) |f| %>     <%= f.hidden_field :url %>     <%= f.text_field :content %>     <%#= f.text_field :collection_id %> # test passing incorrect values     <%= f.collection_select :collection_id, collection.order(:id),:id,:title, include_blank: true %>     <%= f.submit "post", class: "btn btn-primary" %> <% end %> 

the values form go post_controller#create

assuming have established association between user , his/her collections, maybe can try:

unless current_user.collections.find(params[:post][:collection_id]).blank?     @post = current_user.posts.build(url: @url, content: @title) end 

it check if collection belongs user. in case such collection not exist, return nil.

another thing can try if collection associated user is:

current_user.collections.find(params[:post][:collection_id]).posts.build(url: @url, content: @title) 

i not entirely sure if these efficient ways myself, guess should job looking done.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -