Rails的新手。自学。标题几乎总结了我正在构建您的基本博客应用程序并正在开发评论功能。使用了三个不同的表:User,Post,Comment以及每个表之间的标准关联。代码示例如下......
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
评论_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 %>
路由
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
错误参数
{"utf8"=>"✓",
"authenticity_token"=>"wLU6Bv7lBoJZQ1chWgY7kRweok7m/KvylO5zWBXtD3JGr2rz2VFumXSswGuf9thn32uBQU3rT84mTOd6sE5KHQ==",
"comment"=>{"content"=>"THis is a comment"},
"commit"=>"Create Comment",
"post_id"=>"5"}
正如我提到它的禁用属性错误,我知道这与我下面的强参数有关,但我很难过。任何帮助都将很乐意和真诚地受到赞赏。
答案 0 :(得分:1)
尝试以下代码。
@comment = @post.comments.new(comments_params)
您应该将强参数方法传递给模型中的new, create or update
方法。