我在Rails中遇到了多態關聯問題。我有一個應用程序,它應該可以評論不同的型號,如Posts, Images, Projects
Rails 3.1:Polymorphic Association @commentable - 如何做對吧?
現在我只是有帖子發表評論。在開始頁面有一個最新帖子的索引視圖,每個帖子都有一個小的評論表單,通過Ajax進行評論,非常像Facebook。
我的模式是這樣的:
class Post < ActiveRecord::Base
belongs_to :post_category
belongs_to :user
has_many :comments, :as => :commentable
validates_presence_of :user_id
validates_presence_of :post_category_id
validates_presence_of :title
validates_presence_of :body
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
現在在我的評論控制器添加以下方法(我想我把它從railscasts或某事),我認爲嘗試找出@commentable動態當創建評論時。 但這總是返回錯誤undefined method
意見對零:NilClass`
# find commentable (parent) item
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value) unless name == 'user_id'
end
end
nil
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
if @comment.save
redirect_to @comment, :notice => 'Comment was successfully created.'
redirect_to :id => nil
else
render :action => "new"
end
end
的兩件事情我在嘗試部分分別爲:
離開commentable信息表單的
= form_for [@commentable,Comment.new],:remote => true do | f | #new_comment.add_comment = f.hidden_field:user_id,:value => current_user.id = f.text_field:content,:size => 55,:value =>'發表評論...',:class = > 'comment_form' = f.submit 「發送」
和2傳遞commentable_id和commentable_type
= form_for [@commentable, Comment.new], :remote => true do |f|
#new_comment.add_comment
= f.hidden_field :user_id, :value => current_user.id
= f.hidden_field :commentable_id, :value => post_id
= f.hidden_field :commentable_type, :value => 'Post'
= f.text_field :content, :size => 55, :value => 'leave a comment...', :onfocus => 'this.select()', :class => 'comment_form'
= f.submit "send"
既沒有運氣。任何幫助將不勝感激。 整個評論控制器的代碼是在這個要點:https://gist.github.com/1334286
probelem實際上是'@commentable'總是零..所以評論不能被稱爲它。 – tmaximini
可評論的是你的文章,所以你需要區分是否你在PostsController或CommentsController。應該在CommentsController中使用「find_commentable」方法來獲取Post對象(在CommentsController中你肯定不知道它是一個Post - 這就是爲什麼你將它抽象爲「可評論」的原因)。長話短說:在你的PostsController中,在show動作中添加諸如「@commentable = Post.find(params [:id])」。 – emrass
更新了我的答案。所提供的編碼應該足以讓您朝着正確的方向前進。 – emrass