Rails 3:带有to_param的嵌套Restful路由被反转

时间:2012-06-29 11:58:50

标签: ruby-on-rails ruby-on-rails-3

#解释上下文

puts "I am learning Rails, building a simple forum application."
puts "I am pretty satisfied to where I got so far but routes... "
puts "...still figuring them out."
puts "Been 2 days trying all sorts of things."
puts "This is where I am now, and something is not working as expected."
puts "Any help/pointers would be appreciated! :)"

#config / routes.rb

scope "/helpcenter" do
  resources :cat, :controller => "forums", :as => :forums do
    resources :topics , :controller => "forum_topics", :as => :topics
    resources :posts, :controller => "forum_posts", :as => :posts
  end
end

match "/helpcenter" => "forums#index", :as => :forums

#app / models / forum.rb

class Forum < ActiveRecord::Base
  def to_param
    "#{id}-#{name.parameterize}"
  end
end

#app / models / forum_topic.rb

class ForumTopic < ActiveRecord::Base
  def to_param
    "#{id}-#{name.parameterize}"
  end
end

#app / controllers / forums / show.hmtl.erb

link_to @forum_topic.name, forum_topic_path(@forum_topic)
# OR
link_to @forum_topic.name, @forum_topic

#link_to生成什么:

"/helpcenter/cat/1-first-topic/topics/1-first-forum"

#我期望看到的内容(因为主题应该在论坛中):

"/helpcenter/cat/1-first-forum/topics/1-first-topic"

#我做错了什么?

puts "Thanks!"

2 个答案:

答案 0 :(得分:1)

主要路径应为:

forum_topic_path(@forum, @topic)  
forum_topics_path(@forum)

你传入的参数(@forum_topic)

link_to @forum_topic.name, forum_topic_path(@forum_topic)

有一个:id与之关联(1),因此它将显示id = 1的论坛。您还应该传递主题ID

forum_topic_path(@forum, @topic)

感到惊讶的是没有id没有得到错误 - 我猜测它推断了两个资源的id。

答案 1 :(得分:1)

您好我想要生成指向特殊论坛特殊主题的链接。

当你生成链接时,你需要2个ID( - 或2个intances,一个用于论坛,一个用于主题)。

link_to @forum_topic.name, forum_topic_path(@forum, @forum_topic)