Rails generator for nested resources

2

I was searching but did not find any nested resources in Rails. Could anyone tell me if you know any?

    
asked by anonymous 06.03.2015 / 01:27

1 answer

2

Henry, there is no nested resource generator, but Rails makes it a lot easier to do this at hand.

In the case of Article has many Comments , you would basically need to change:

a) The models:

class Article < ActiveRecord::Base
  has_many :comments
end

class Article < ActiveRecord::Base
  belongs_to :article
end

b) The routes:

resources :articles do
  resources :comments
end

c) And finally, the controllers: (this part can be tricky)

comments_controller.rb

class CommentsController < ApplicationController
  def index
    @article = Article.find(params[:article_id])
    @comments = @article.comments
  end

  def new
    @article = Article.find(params[:article_id])
    @comment = @article.comments.build
  end

  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.build(params[:comment])
    if @comment.save
      flash[:notice] = "Successfully created comment."
      redirect_to article_url(@comment.article_id)
    else
      render :action => 'new'
    end
  end

  def edit
    @comment = Comment.find(params[:id])
  end

  def update
    @comment = Comment.find(params[:id])
    if @comment.update_attributes(params[:comment])
      flash[:notice] = "Successfully updated comment."
      redirect_to article_url(@comment.article_id)
    else
      render :action => 'edit'
    end
  end

  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
    flash[:notice] = "Successfully destroyed comment."
    redirect_to article_url(@comment.article_id)
  end
end

articles_controller.rb

class ArticlesController < ApplicationController
  def index
    @articles = Article.find(:all)
  end

  def show
    @article = Article.find(params[:id])
    @comment = Comment.new(:article => @article)
  end

  def new
    @article = Article.new
  end

  def create
    @article = Article.new(params[:article])
    if @article.save
      flash[:notice] = "Successfully created article."
      redirect_to @article
    else
      render :action => 'new'
    end
  end

  def edit
    @article = Article.find(params[:id])
  end

  def update
    @article = Article.find(params[:id])
    if @article.update_attributes(params[:article])
      flash[:notice] = "Successfully updated article."
      redirect_to @article
    else
      render :action => 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy
    flash[:notice] = "Successfully destroyed article."
    redirect_to articles_url
  end
end

Following the model illustrated above you should not have problems =)

Any more specific questions, you can ask a new question!

    
28.04.2015 / 18:59