socksocket
socksocket

Reputation: 4371

Rails - passing object's id

I'm creating a message-board site using ruby on rails.
I generated two scaffolds: Topic and Forum. Topic belongs_to Forum.

when the user is creating a new topic, I should pass the forum_id (a GET var). something like:
http://example.com:3000/topics/new/1

and then, when the user submit the form he passes back the forum_id with the POST request (through hidden html field?).

what is the right way doing it?
thanks

routes:

  resources :forums

  get "admin/index"

  resources :posts

  resources :topics

  resources :users

  match '/signup', :to => 'users#new'

  get   '/login', :to => 'sessions#new', :as => :login
  match '/auth/:provider/callback', :to => 'sessions#create'
  match '/auth/failure', :to => 'sessions#failure'

  match '/topics/new/:id', :to => 'topics#new'

Upvotes: 1

Views: 182

Answers (1)

Ahmad Sherif
Ahmad Sherif

Reputation: 6223

A good way to do it is to nest topics resources inside forums resources like this:

resources :forums do
  resources :topics
end

Then in your TopicsController

class TopicsController < ApplicationController
  def new
    @forum = Forum.find params[:forum_id]
    @topic = Topic.new
  end

  def create
    @forum = Forum.find params[:forum_id] # See the redundancy? Consider using before_filters
    @topic = @forum.topics.build params[:topic]

    if @topic.save
      redirect_to @topic
    else
      render action: :new
    end
  end
end

And finally in your views/topics/_form.html.erb:

<%= form_for [@forum, @topic] do |f| %>
  # Your fields
<% end %>

Upvotes: 2

Related Questions