In my Rails 4 app I have two models - users and accommodations. Users has many accommodations and it has been set up in the relevant models (i.e. belongs_to, has_many, etc). I'm trying to validate data added to my accommodations model and display errors if there are any.
When I try to access accommodations/new action, I get the following error:
NoMethodError in Accommodations#new
undefined method `errors' for nil:NilClass
I have this working for when my users try and register and here is the code:
users/new.html.erb:
<% if @user.errors.any? %>
<% @user.errors.full_messages.each do |msg| %>
<p class="error"><%= msg %></p>
<% end %>
<% end %>
but when I try to do the same with accommodation I get the error mentioned:
accommodations/new.html.erb:
<% if @accommodation.errors.any? %>
<% @accommodation.errors.full_messages.each do |msg| %>
<p class="error"><%= msg %></p>
<% end %>
<% end %>
After reading around I realise that the first one works because of this in the UsersController:
def new
@user = User.new
end
but after trying the following in my AccommodationsController #new action it still won't work
@accommodation = Accommodation.new
My Accommodation model is as follows:
class Accommodation < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
end
build_accommodation