Reputation: 68
I have reviewed the code from 200 times. Maybe I can help you find a wizard who breaks the whole. I create a room entry that is connected with the hotel but also with the account. I do not have any problems writing data. Until I do not pass data through validation. When the validation is also fulfilled, the data is saved, but when I do not want to meet their expectations, it is natural to flash errors, but unfortunately I can not find the error method.
undefined method `errors' for Room::ActiveRecord_Associations_CollectionProxy:0x00007ff8b2a36530
<% if @room.errors.full_messages.any? %>
<div class="error_explanation">
<h2><%= t('other.errors', :count => @room.errors.full_messages.size) %></h2>
<ul>
<% @room.errors.full_messages.each do |error_message| %>
<li><%= error_message %></li>
<% end %>
</ul>
</div>
<% end %>
My controller
def new
@account = Account.find(current_user.account_id)
@room = @account.rooms.new
@hotels = @account.hotels.all
rescue ActiveRecord::RecordNotFound
flash[:error] = "#{t 'alerts.Not_found'}"
redirect_to(rooms_manages_path)
end
def create
@account = Account.find(current_user.account_id)
@room = @account.rooms
@hotels = @account.hotels.all
if @room.create(room_params).valid?
flash[:success] = "#{t 'alerts.Is_save'}"
redirect_to(rooms_manages_path)
else
flash[:warning] = "#{t 'alerts.If_save'}"
render 'new'
end
rescue ActiveRecord::RecordNotFound
flash[:error] = "#{t 'alerts.Not_found'}"
redirect_to(rooms_manages_path)
end
My model
class Room < ApplicationRecord
belongs_to :account
belongs_to :hotel
has_many :reservations
mount_uploaders :images, ImagesroomUploader
serialize :images, JSON # If you use SQLite, add this line.
validates :name, presence: true
end
class Account < ApplicationRecord
has_many :users, inverse_of: :account, dependent: :destroy
has_many :hotels
has_many :rooms
has_many :offers
has_many :reservations
has_many :widgets
has_many :accountsinvoices
has_many :accountspayments
end
My view
<%= form_for(:room, :url => rooms_manages_create_path(), :html => {:id => "form"}) do |f| %>
<% if @room.errors.full_messages.any? %>
<div class="error_explanation">
<h2><%= t('other.errors', :count => @room.errors.full_messages.size) %></h2>
<ul>
<% @room.errors.full_messages.each do |error_message| %>
<li><%= error_message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<div class="text-left">
<%= submit_tag("#{t 'other.actions.save'}", class: 'btn btn-primary') %>
</div>
<% end %>
Upvotes: 0
Views: 150
Reputation: 2476
Your create
action sets @room
to a collection
@room = @account.rooms
hence your error message in the view. Instead, try
# some code ommitted ...
@room = @account.rooms.create(room_params)
@hotels = @account.hotels.all
if @room.valid?
# some code ommitted ...
Upvotes: 2