Rails 3:如何将新主题与论坛相关联

时间:2012-06-06 08:11:44

标签: ruby-on-rails-3 associations

我正在尝试用Ruby on Rails编写一个论坛。

在模型方面,我完成了主题和论坛之间的关联

# 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

如何更改topic_controller的newcreate以确保为当前论坛而非其他论坛创建主题?

例如,如果我从id为1的论坛创建新主题,如何确保创建新主题的forum_id = 1?

2 个答案:

答案 0 :(得分:2)

使用nested resources

resources :forums do
  resources :topics
end

您将拥有类似

的路径
/forums/:forum_id/topics/new

然后在TopicsController

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

答案 1 :(得分:1)

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