Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
JavaScript CSS Ruby
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
app
bin
config
db
lib
log
public
test
vendor/assets
.gitignore
Gemfile
Gemfile.lock
README.md
Rakefile
config.ru

README.md

Generate Plate

rails generate scaffold plate number:string state:string

Examine generated files

Add Validations

validates :number, {:presence => true, :length => {:is => 7}}
validates :state, {:presence => true, :length => {:is => 2}}

Add Callback

before_save :format_values

def format_values
  self.state = self.state.upcase
  self.number = self.number.upcase
end

Add Complaints Model

rails generate resource complaint name:string message:text plate_id:integer
rake db:migrate

Update Routes

resources :plates do
  resources :complaints
end

Add Associations

has_many :complaints
belongs_to :plate

Test in console

Add Complaint Form

Plate Controller

@complaint = @plate.complaints.build

plate#show complaint form

<%= form_for [@plate, @complaint] do |f| %>
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :message %>
    <%= f.text_area :message %>
  </div>
  <%= f.submit %>
<% end %>

PlatesController#create

def create
  @plate = Plate.find(params[:plate_id])
  @complaint = @plate.complaints.new(complaint_params)
  if @complaint.save
    redirect_to @plate
  else
    render '/plates/show'
  end
end

private

def complaint_params
  params.require(:complaint).permit(:name, :message)
end

plate#show list complaints

<div class="complaints">
  <% @plate.complaints.each do |complaint| %>
    <div class="complaint">
      <strong><%= complaint.name %></strong>
      <p><%= complaint.message %></p>
    </div>
  <% end %>
</div>

Add Complaint Validations

validates :name, :presence => true
validates :message, :presence => true
Something went wrong with that request. Please try again.