2012-06-06 32 views
0

我正在嘗試使用Ruby on Rails編寫論壇。Rails 3:如何將新主題與論壇相關聯

在模型方面,我主題和論壇

之間完成關聯
# forum.rb 
class Forum < ActiveRecord::Base 
    has_many :topics 

    attr_accessible :name, :description 
end 

# topic.rb 
class Topic < ActiveRecord::Base 
    has_many :posts 
    belongs_to :forum 
end 

控制器論壇

# forums_controller.rb 
class ForumsController < ApplicationController 
    def new 
    @forum = Forum.new 
    end 

    def create 
    @forum = Forum.new(params[:forum]) 
    if @forum.save 
     flash[:success] = "Success!" 
     redirect_to @forum 
    else 
     render 'new' 
    end 
    end 

    def index 
    @forums = Forum.all 
    end 

    def show 
    @forum = Forum.find(params[:id]) 
    end 
end 

控制器主題

class TopicsController < ApplicationController 
    def new 
    @topic = current_forum???.topics.build 
    end 

    def create 
    @topic = Topic.new(params[:topic]) 
    if @topic.save 
     flash[:success] = "Success!" 
     redirect_to @topic 
    else 
     render 'new' 
    end 
    end 

    def index 
    @topics = Topic.all 
    end 

    def show 
    @topic = Topic.find(params[:id]) 
    end 
end 

如何更改newcreate for topics_controller,以確保主題是爲目前論壇而不是其他人創建的?

因此,例如,如果我從id = 1的論壇創建新主題,如何確保forum_id = 1以創建新主題?

回答

2

使用nested resources

resources :forums do 
    resources :topics 
end 

你會在你的TopicsController

def new 
    @forum = Forum.find(params[:forum_id]) 
    @topic = @forum.topics.build 
end 
+0

這似乎非常相似,我期待像

/forums/:forum_id/topics/new 

然後路徑。要從論壇的「show」頁面創建到'new'主題頁面的鏈接,我可以這樣做嗎? '<%= link_to「新主題」,forum_topic_new_path%>' –

+0

這將是'new_forum_topic_path'。使用[rake routes](http://guides.rubyonrails.org/routing.html#seeing-existing-routes-with-rake)列出你的路線。 – Stefan

1
class TopicsController < ApplicationController 
    def new 
    @forum = Forum.find(params[:id]) 
    @topic = @forum.topics.build 
    end