我正在尝试关注Ryan Bates多态模型教程(Rails 3),以在我的照片模型中实现注释。我在尝试为照片创建新评论时遇到了麻烦,因为我在Rails 4中并且我必须处理:评论强参数。
我有嵌套资源
#Nesting Resources
resources :users do
resources :photos do
resources :comments
resources :tags
end
end
所以路线应该是/ users / friendly-id / photos / friendly-id / comments,但是它构造得很糟糕,我的表格中有<%= form_for [@user, @commentable, @comment] do |f| %>
。
照片控制器
#create
def show
@photo = Photo.friendly.find(params[:id])
@user = @photo.user
@tag = Tag.new
@tag.photo_id = @photo.id
@category = Category.all
@commentable = @photo
@comments = @commentable.comments
@comment = Comment.new
@zone = Zone.all
respond_to do |format|
format.html #show.html.erb
format.json {render json: @photo}
end
end
表格
<%= form_for [@user, @commentable, @comment] do |f| %>
<% if @comment.errors.any? %>
<div class="error_messages">
<h2>Please correct the following errors.</h2>
<ul>
<% @comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
评论控制器
class CommentsController < ApplicationController
before_filter :load_commentable
def index
@comments = @commentable.comments
end
def new
@comment = @commentable.comments.new
end
def create
@comment = @commentable.comments.new(comment_params)
if @comment.save
redirect_to @commentable, notice: "Comment created."
else
render :new
end
end
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
@commentable = resource.singularize.classify.constantize.find(id)
end
def comment_params
require(:comment).permit(:photo_id, :user_id, :content)
end
###Error 2: When I put friendly.id instead of only id in `load_commentable` method I get a Forbidden Attribute error.
end
请有人帮忙!谢谢