Reputation: 1
Forgive me I'm new at Ruby. I am trying to create a site to contain information about a zoo.
I have an enclosure
model and an animal
model.
This is my code for the create
method in animal_controller
def create
if params.has_key?(:enclosure_id)
@enclosure = Enclosure.find(params[:enclosure_id])
@animal = Animal.new(animals_params)
@animal.user_id = current_user.id
if @animal.save
@enclosure.animals.push(@animal)
redirect_to enclosure_path(@enclosure)
else
# ????
end
else
@animal = Animal.new(animal_params)
@animal.user_id = current_user.id
if @animal.save
redirect_to @animal
else
render 'new'
end
end
end
I then have two places where a new animal can be created. One is using a form at localhost:3000/animals/new
. The other is using a similar form on the show
page of a particular enclosure, so for example at localhost:3000/enclosures/1/
In my code above, I check for the presence of enclosure_id
to determine where the call is coming from. If the parameter is found, I add the animal to the enclosure there and then. However, if @animal.save
fails, I do not understand how I can return to the localhost:3000/enclosures/id
page with the validation error messages being passed. In the case of no enclosure_id
, render 'new'
takes the user back to the ../animal/new
page with error messages passed as well.
Thanks
Upvotes: 0
Views: 713
Reputation: 165
I don't think it's a good idea to go to an other page, because you will have to serialize errors linked to the model and it's gonna be complicated and ugly.
I think you should render the show page of the enclosure and then display the errors
#....
if @animal.save
@enclosure.animals.push(@animal)
redirect_to enclosure_path(@enclosure)
else
render 'enclosures/show'
end
#....
Upvotes: 1