Question

I am struggling with passing :project_id value into :comments model while having nested resources. Hash that is passing from form looks like this:

Parameters: {"utf8"=>"✓", 
"comment"=>{"title"=>"sdfs", "desc"=>"ddf"}, 
"commit"=>"Create Comment", 
"project_id"=>"1"}

And my permit attributes method as below:

params.require(:comment).permit(:title, :desc, :product_id)

I was also trying with code as such:

  #params.permit(:project_id, comments: [ :title, :desc])
  #params.require(:project_id).permit(:project_id)
  #params.require(:comment).permit(:title, :desc)

And my resources:

  resources :projects do
    resources :comments
  end

Problem is that :title and :desc are inserted but :project_id not... Could you tell me what I am doing wrong? Thank you in advance!

EDIT:// Form that I am using:

<%= form_for([@project, @comment]) do |f| %>
  <% if @comment.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>

      <ul>
      <% @comment.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :desc %><br>
    <%= f.text_field :desc %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
Was it helpful?

Solution 2

You need to call #require multiple times:

params.require(:project_id)
params.require(:comment).permit(:title, :desc)

See: https://github.com/rails/strong_parameters#require-multiple-parameters

Alternatively, you could pass the project_id via a hidden field in the form:

<%= f.hidden_field :project_id, value: @project.id %>

This would include the project_id as a nested attribute in the comment. Then you could use:

params.require(:comment).permit(:title, :desc, :project_id)

OTHER TIPS

Try this

params.permit(:project_id, comment: [ :title, :desc])

Note that its comment and not comments

Wrong, maybe, in this sentence

params.require(:comment).permit(:title, :desc, :product_id)

Need :project_id

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top