Search code examples
ruby-on-railsrubystrong-parameters

Yet another forbidden attributes error - cannot find where I am going wrong with this


New to Rails. Self teaching. The title pretty much sums it up I'm building your basic blog app and am working on a comment functionality. Three different tables being used: User, Post, Comment with the standard associations among each. Code samples are below...

CommentsController

def new
    @post = Post.find(params[:post_id])
    @comment = Comment.new
end

def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.new(params[:comment]) #throwing the attributes error here
   @user = current_user
    if @comment.save
        redirect_to root_path
    else
        render 'new'
    end
end

private

  def comment_params
    params.require(:comment).permit(:user_id, :post_id, :content)
  end

comments _form.html.erb

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

      <ul>
      <% @comment.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field-content">
    <%= f.label :content %><br>
    <%= f.text_area :content, size: "60x5" %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

routes

Rails.application.routes.draw do
  root                      'visitors#index'
  get           '/about',   to: 'visitors#about'
  get           '/show',    to: 'visitors#show'
  get           '/login',   to: 'sessions#new'
  post          '/login',   to: 'sessions#create'
  get           '/logout',  to: 'sessions#destroy'

  resources         :visitors, only:[:index]
  resources         :posts
  resources         :users

  resources :posts, :shallow => true do 
    resources :comments
  end
end

Error parameters

{"utf8"=>"✓",
 "authenticity_token"=>"wLU6Bv7lBoJZQ1chWgY7kRweok7m/KvylO5zWBXtD3JGr2rz2VFumXSswGuf9thn32uBQU3rT84mTOd6sE5KHQ==",
 "comment"=>{"content"=>"THis is a comment"},
 "commit"=>"Create Comment",
 "post_id"=>"5"}

As I mentioned its a forbidden attributes error and I know that relates to the strong parameters that I have below but I am seriously stumped. Any help will gladly and sincerely be appreciated.


Solution

  • Try the code below.

    @comment = @post.comments.new(comments_params)
    

    You should pass your strong parameters method to new, create or update methods in the model.