0
设置多态时遇到了很多麻烦。我有评论工作正常,但链接应该工作完全一样的链接#索引中有NameError。如果我尝试forum_posts/1 /评论一切都很好,但不是forum_posts/1/links。多态未初始化常量
我是继railscast教程http://railscasts.com/episodes/154-polymorphic-association?view=asciicast
欣赏的帮助。
错误
NameError在链接#索引
未初始化的常数ForumPost ::链接 提取的源(围绕线#4):
1: <h1>Links</h1>
2:
3: <ul id="links">
4: <% @links.each do |link| %>
5: <li><%= link.display_name %></li>
6: <% end %>
7: </ul>
路由
种resources :forum_posts do
resources :comments
resources :links
end
模式
*型号/ forum_posts.rb *
class ForumPost < ActiveRecord::Base
attr_accessible :content, :display_name, :section, :user_id
has_many :comments, :as => :commentable
has_many :links, :as => :linkable
end
型号/ comments.rb
class Comment < ActiveRecord::Base
attr_accessible :commentable_id, :commentable_type, :content, :user_id
belongs_to :commentable, :polymorphic => true
end
型号/ comments.rb
class Links < ActiveRecord::Base
attr_accessible :description, :display_name, :inamge, :linkable_id, :linkable_type, :user_id
belongs_to :linkable, :polymorphic => true
end
控制器
*控制器/ comments_controller.rb *
class CommentsController < ApplicationController
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
def index
@commentable = find_commentable
@comments = @commentable.comments
end
def create
@commentable = find_commentable
@comment = @commentable.comments.build(params[:comment])
if @comment.save
flash[:notice] = "Successfully saved comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
end
*控制器/ links_controller.rb *
class LinksController < ApplicationController
def find_linkable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
def index
@linkable = find_linkable
@links = @linkable.links
end
def create
@linkable = find_linkable
@link = @linkable.links.build(params[:link])
if @link.save
flash[:notice] = "Successfully saved link."
redirect_to :id => nil
else
render :action => 'new'
end
end
end
浏览
的意见/评论/ index.html.erb
<h1>Comments</h1>
<ul id="comments">
<% @comments.each do |comment| %>
<li><%= comment.content %></li>
<% end %>
</ul>
<h2>New Comment</h2>
<%= form_for [@commentable, Comment.new()] do |form| %>
<%= form.label :content %><br/>
<%= form.text_area :content, :rows => 5 %><br/>
<%= form.submit "Add comment" %>
<% end %>
的意见/链接/ index.html.erb
<h1>Links</h1>
<ul id="links">
<% @links.each do |link| %>
<li><%= link.display_name %></li>
<% end %>
</ul>
<h2>New Link</h2>
<%= form_for [@linkable, Link.new()] do |form| %>
<%= form.label :display_name %><br/>
<%= form.text_area :display_name %><br/>
<%= form.submit "Add link" %>
<% end %>
非常感谢瑞恩。本周末的大部分时间都在尝试对此进行分类。 :) – otissv 2012-07-09 11:16:25