1

# 解释上下文

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! :)"

# 配置/路由.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

# 应用程序/模型/forum_topic.rb

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

# 应用程序/控制器/论坛/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!"
4

2 回答 2

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 。

于 2012-06-29T12:31:02.003 回答
1

嗨,我认为您想生成一个指向特殊论坛的特殊主题的链接。

因此,当您生成链接时,您需要 2 个 ID( - 或 2 个实例,一个用于论坛,一个用于主题)。

link_to @forum_topic.name, forum_topic_path(@forum, @forum_topic)
于 2012-06-29T12:35:09.783 回答