mercredi 15 juillet 2015

NoMethodError undefined method 'each' fir nil:NilClass

I'm facing NoMethodError in NewFormsController#create, undefined method `each' for nil:NilClass !

Here is my code :

Controller : new_forms_controller.rb

class NewFormsController < ApplicationController
  def new
   @form = NewForm.new
end

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

Model : new_form.rb

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

  attr_accessor :titleID, :articleID, :content, :author

  validates :titleID, :articleID, :content, :author, :presence => true
  validates :titleID, :articleID => {:minimum => 5 }

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

  def persisted?
    false
  end

end

New View : new.html.erb

<% @form.errors.full_messages.each do |msg| %>
    <p><%= msg %></p>
<% end %>

<p>
  <%= f.label :titleID %> <br/>
  <%= f.text_field :titleID %><br/>
</p>
<p>
  <%= f.label :articleID %><br/>
  <%= f.text_field :articleID %><br/>
</p>
<p>
  <%= f.label :content %><br/>
  <%= f.text_field :content %><br/>
</p>
<p>
  <%= f.label :author %><br/>
  <%= f.text_field :author %><br/>
</p>

<p><%= f.submit "Submit"  %></p>

Routes : routes.rb

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

I'm trying to implement ActiveModel because I don't want my form object to be backed up by database, I will have different service for database interactions.

Aucun commentaire:

Enregistrer un commentaire