Skip to content

Instantly share code, notes, and snippets.

@maclover7
Created October 25, 2014 02:17
Show Gist options
  • Save maclover7/14c9d6eaa0c6731a3ecf to your computer and use it in GitHub Desktop.
Save maclover7/14c9d6eaa0c6731a3ecf to your computer and use it in GitHub Desktop.
Rails Sub-resources Routing error
<%= form_for [@person, @joke] do |f| %>
<% if @joke.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@joke.errors.count, "error") %> prohibited this joke from being saved:</h2>
<ul>
<% @joke.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :body %><br>
<%= f.text_area :body %>
</div>
<%= f.hidden_field :person_id %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
class JokesController < ApplicationController
before_action :set_joke, only: [:show, :edit, :update, :destroy]
# GET /jokes
# GET /jokes.json
def index
@jokes = Joke.all
end
# GET /jokes/1
# GET /jokes/1.json
def show
end
# GET /jokes/new
def new
@joke = Joke.new
end
# GET /jokes/1/edit
def edit
end
# POST /jokes
# POST /jokes.json
def create
@joke = Joke.new(joke_params)
respond_to do |format|
if @joke.save
format.html { redirect_to @joke, notice: 'Joke was successfully created.' }
format.json { render :show, status: :created, location: @joke }
else
format.html { render :new }
format.json { render json: @joke.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /jokes/1
# PATCH/PUT /jokes/1.json
def update
respond_to do |format|
if @joke.update(joke_params)
format.html { redirect_to @joke, notice: 'Joke was successfully updated.' }
format.json { render :show, status: :ok, location: @joke }
else
format.html { render :edit }
format.json { render json: @joke.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jokes/1
# DELETE /jokes/1.json
def destroy
@joke.destroy
respond_to do |format|
format.html { redirect_to jokes_url, notice: 'Joke was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_joke
@joke = Joke.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def joke_params
params.require(:joke).permit(:body, :person_id)
end
end
Rails.application.routes.draw do
resources :people do
resources :jokes
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment