JCD JCD - 10 months ago 60
Ruby Question

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...


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

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
render 'new'


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

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>

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


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

Error parameters

"comment"=>{"content"=>"THis is a comment"},
"commit"=>"Create Comment",

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.

Answer Source

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.