Hi. I have a form in my app which, for some reason is not saving any
objects to the database. After clicking submit it redirects back to
itself, but it dosent give any information as to what is going wrong.
Hi. I have a form in my app which, for some reason is not saving any
objects to the database. After clicking submit it redirects back to
itself, but it dosent give any information as to what is going wrong.
We would need to see the code for your 'create' action in your auctions_controller.rb
respond_to do |format|
if @item.save
flash[:notice] = 'Item was successfully created.'
format.html { redirect_to(@item) }
format.xml { render :xml => @item, :status => :created, :location => @item }
else
format.html { render :action => "new" }
format.xml { render :xml => @item.errors, :status => :unprocessable_entity }
end
end
end
Everything looks good there. You said it's redirecting back on itself. I assume you mean that it's going back to the 'new' action, which is what you have it doing if the save fails (which is good). So, make sure you have the following in your new.html.erb file...
<%= error_messages_for :auction %>
That should hopefully give you a hint why the save is failing. Probably some validations you have setup that aren't passing.
# Auction controller:
def create
@cats = Category.find(:all)
params[:auction][:user_id] = current_user.id
@auction = Auction.new(params[:auction])
respond_to do |format|
if @auction.save
flash[:notice] = 'Auction was successfully created.'
format.html {
redirect_to(@auction)
}
format.xml {
render :xml => @auction, :status => :created, :location => @auction
}
else
format.html {
render :action => "new"
}
format.xml {
render :xml => @auction.errors, :status => :unprocessable_entity
}
end
end
end
# I also have an items controller, with a create action which is pretty much identical, but works just fine.
# Item controller:
def create
@cats = Category.find(:all)
params[:item][:user_id] = current_user.id
@item = Item.new(params[:item])
respond_to do |format|
if @item.save
flash[:notice] = 'Item was successfully created.'
format.html {
redirect_to(@item)
}
format.xml {
render :xml => @item, :status => :created, :location => @item
}
else
format.html {
render :action => "new"
}
format.xml {
render :xml => @item.errors, :status => :unprocessable_entity
}
end
end
end
As the @J_Garvin said, you want to output the errors somewhere, but error_message_for is not a part of Rails. You want to use the method full_messages that is on the errors object you get on an invalid ActiveRecord. Check out the Rails API docs for the details, but that method gives you an array of error messages. You can view this in one of three ways:
In your controller do Rails.logger.info @auction.errors.full_messages.join(",")
In your view, do `<%= @auction.errors.full_messages(“,”) %>
Drop a binding.pry right before render and examine the contents of @auction.errors