gpt4 book ai didi

ruby-on-rails - 带注释的多态关联 - Ruby on Rails

转载 作者:行者123 更新时间:2023-12-04 06:45:58 25 4
gpt4 key购买 nike

我在让这些多态关联完全工作时遇到了一些麻烦。我跟着这个教程www.railscasts.com/episodes/154-polymorphic-association ,但这似乎只有在我发布新帖子时是路径/controller/ID#/comments 时才有效。如果我尝试在/controller/ID# 上呈现部分评论表单,则会在创建评论时收到此错误:

undefined method `comments' for #<ActiveSupport::HashWithIndifferentAccess:0x10341b2d0>

我有三个模型:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end


class Post < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :commentable
end

class Article < ActiveRecord::Base
belongs_to :user
has_many :comments, :as => :commentable
end

这是我对/articles/#{ID} 的看法
<%= @article.title %>
<%= @article.content %>
<%= @article.user.login %>
<%= link_to 'Edit Article', edit_article_path(@article) %>

<h2>Comments</h2>
<%= render "comments/comments" %>
<%= render "comments/comment" %>

这是我的部分评论:
<div class="post_comment">
<%= form_for [@commentable, Comment.new] do |f| %>
<%= f.text_area :content %>
<%= f.submit "Post" %>
<% end %>
</div>

这是我在评论 Controller 中的 create 方法:
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
@comment.user_id = current_user.id
if @comment.save
redirect_to :id => nil
else
flash[:notice] = "something went wrong"
redirect_to @commentable
end
end

def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end

我想我明白问题是什么,但不确定如何解决问题。此表单正在寻找@commentable,但如果路径不是嵌套的,则它找不到@commentable(可能是错误的)。

以下是我的路线:
devise_for :users do
get "login", :to => "devise/sessions#new"
get "register", :to => "devise/registrations#new"
end

resources :posts do
resources :comments
resources :tags
end

resources :articles do
resources :comments
resources :tags
end

resources :users do
resources :articles
resources :comments
resources :tags
resources :posts
end

resources :comments

root :to => "home#index"

end

最佳答案

您的问题是 find_commentable 正在返回 params 哈希本身,因为 return 语句从未被触发。
我通过错误消息推断出这一点,因为 params.class == ActiveSupport::HashWithIndiffrentAccess

def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end
我会添加类似的东西
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
raise ActiveRecord:NoRecord.new("Couldn\'t find it captain!")
end
我认为上面的异常类型是正确的,如果没有看到 Comment.find_by_id(-1) 或类似的东西会引发什么。应该是这样的。
编辑
我建议抛出异常的原因是 ApplicationController 应该在人们开始浏览并访问 example.com/posts/9001 时捕获它们并优雅地处理它们

关于ruby-on-rails - 带注释的多态关联 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com