Rails 4 - Validate Model without a database
Asked Answered
F

3

2

I've followed this tutorial and molding it as best I can for Rails 4.

http://railscasts.com/episodes/219-active-model?language=en&view=asciicast


class Contact
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  validates :name, :email, :phone, :comment, :presence => true

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

  def persisted?
    false
  end

  private
  # Using a private method to encapsulate the permissible parameters is just a good pattern
  # since you'll be able to reuse the same permit list between create and update. Also, you
  # can specialize this method with per-user checking of permissible attributes.
  def contact_params
    params.require(:contact).permit(:name, :email, :phone, :comment)
  end
end

In my Controller:

class ContactController < ApplicationController
  def index
    @contact = Contact.new
  end

  def create
    @contact = Contact.new(params[:contact])
    if @contact.valid?
      # Todo send message here.
      render action: 'new'
    end
  end
end

And in my View:

<%= form_for @contact do |f| %>
    <%= f.label :name %>:
    <%= f.text_field :name %><br />

    <%= f.label :email %>:
    <%= f.text_field :email %><br />

    <%= f.submit %>
<% end %>

I'm getting this exception message:

undefined method `name' for #<Contact:0x007fd6b3bf87e0>
Fracas answered 31/5, 2013 at 20:54 Comment(0)
T
4

you have to declare them as attributes.

attr_accessor :name, email, :phone, :comment

Tophus answered 31/5, 2013 at 22:23 Comment(0)
H
1

you can use the ActiveAttr gem: https://github.com/cgriego/active_attr

Rails Cast Tutorial: http://railscasts.com/episodes/326-activeattr

Example:

class Contact
  include ActiveAttr::Model

  attribute :name
  attribute :email
  attribute :phone
  attribute :comment

  validates :name, :email, :phone, :comment, :presence => true
end

PS: I know, it's an old question, but this can help someone.

Heptangular answered 14/4, 2015 at 14:37 Comment(0)
A
1

It's actually simpler in Rails 4 and up: use ActiveModel::Model instead like so:

class Contact
  include ActiveModel::Model
  attr_accessor :name, :email, :phone, :comment

  validates :name, :email, :phone, :comment, :presence => true
end
Anklet answered 29/5, 2017 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.