I have some trouble. I have 3 models : Forum Topic Post Forum
has_many :topics, dependent: :destroy
Topic
belongs_to :forum
has_many :posts, dependent: :destroy
Post belongs_to :topic
Forum controller
class ForumsController < ApplicationController
def index
@forums = Forum.all
end
def show
@forum = Forum.find(params[:id])
@topics = Topic.all
end
end
Topic controller
class TopicsController < ApplicationController
def create
@forum = Forum.find(params[:forum_id])
@topic = @forum.topics.create(topic_params)
if @topic.save
redirect_to root_path
end
end
def new
@forum = Forum.find(params[:forum_id])
@topic = Topic.new
end
def show
@forum = Forum.find(params[:forum_id])
@topics = Topic.find(params[:id])
end
private
def topic_params
params.require(:topic).permit(:name, :created_at, :last_poster_id => current_user.id, :last_post_at => Time.now)
end
end
routes.rb
resources :forums do
resources :topics
end
forum/show
- @forum.topics.each do |f|
= link_to f.name, forum_topic_path[@forum, @topic]
rake routes:
forum_topics GET /forums/:forum_id/topics(.:format) topics#index
POST /forums/:forum_id/topics(.:format) topics#create
new_forum_topic GET /forums/:forum_id/topics/new(.:format) topics#new
edit_forum_topic GET /forums/:forum_id/topics/:id/edit(.:format) topics#edit
forum_topic GET /forums/:forum_id/topics/:id(.:format) topics#show
PATCH /forums/:forum_id/topics/:id(.:format) topics#update
PUT /forums/:forum_id/topics/:id(.:format) topics#update
DELETE /forums/:forum_id/topics/:id(.:format) topics#destroy
forums GET /forums(.:format) forums#index
POST /forums(.:format) forums#create
new_forum GET /forums/new(.:format) forums#new
edit_forum GET /forums/:id/edit(.:format) forums#edit
forum GET /forums/:id(.:format) forums#show
PATCH /forums/:id(.:format) forums#update
PUT /forums/:id(.:format) forums#update
DELETE /forums/:id(.:format) forums#destroy
but i have error
No route matches {:action=>"show", :controller=>"topics", :id=>"1"} missing required keys: [:forum_id]
idn how to create this is nested links... help me
Here's how to get it working:
#config/routes.rb
resources :forums do
resources :topics
end
#app/models/forum.rb
class Forum < ActiveRecord::Base
has_many :topics
end
#app/models/topic.rb
class Topic < ActiveRecord::Base
belongs_to :forum
end
#app/controllers/forums_controller.rb
class ForumsController < ApplicationController
def show
@forum = Forum.find params[:id]
@topics = @forum.topics
end
end
#app/views/forums/show.html.erb #-> url.com/forums/5
<% @topics.each do |topic| %>
= link_to topic.name, forum_topic_path(@forum.id, topic.id)
<% end %>