jeudi 16 juillet 2015

Convert resource routes in Rails to non-resource routes

I have implemented this simple form using non-db backed models. And I'm able to perform validations and showing form fields on it. But I have implemented this using resource. Now I want to learn about how to add more actions, apart from CRUD into this, and defining routes for them. Or if I want to stop using resources, and explicitly define paths for actions. How should I proceed with this.

My files :

Controller : new_forms_controller.rb

class NewFormsController < ApplicationController
  def new
   @form = NewForm.new
   flash[:notice] = nil
  end

  def index

  end

  def create
    @form = NewForm.new(params[:new_form])
    if @form.valid?
      flash[:notice] = "Successfully created recommendation."
      render :action => 'show'
    else
      render :action => 'new'
    end
  end

  def show

  end

end

Model : new_form.rb

class NewForm
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Naming

  attr_accessor :title, :article, :content, :author

  validates :title, :article, :content, :author, :presence => true
  validates :title, :article => {:minimum => 5 }

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

end

Routes : route.rb

TestBranch::Application.routes.draw do
  resources :new_forms
  root :to => "new_forms#new"
end

Aucun commentaire:

Enregistrer un commentaire