Jason Kim
Jason Kim

Reputation: 19031

Rails 3: How to associate a new Topic with a Forum

I am trying to write a forum with Ruby on Rails.

On model side, I finished association between Topic and Forum

# 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

Controller for Forum

# 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

Controller for Topic

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

How do I change new and create for topics_controller to make sure the topic is created for current forum rather than some other one?

So for example, if I create a new topic from a forum with id=1, how do I make sure that forum_id=1 for the new topic created?

Upvotes: 0

Views: 400

Answers (2)

Stefan
Stefan

Reputation: 114178

Using nested resources

resources :forums do
  resources :topics
end

you will have a path like

/forums/:forum_id/topics/new

then in your TopicsController

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

Upvotes: 2

iAmDecim
iAmDecim

Reputation: 403

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

Upvotes: 1

Related Questions