1
我正在開發一種首次在大自然中下載的表單。隨着一些你的幫助,我已經成功迄今,但在這一點上,我創建了應用程序/ index.html.erb頁:我的索引頁如何寫入才能顯示數據?
<% @jobs.each do |job| %>
<h2><%= @job.category %></h2>
<p><%= @job.poster %></p>
<% end %>
上面的代碼渲染以下錯誤:
NoMethodError in Jobs#index
undefined method `category' for nil:NilClass
我以爲代碼告訴我,我沒有類別,我做了,所以我更新類別以及其他軌道控制檯中的其他人,但我繼續收到此錯誤,我不知道爲什麼以及如何解決它。
在我的應用程序/ show.html.erb則代碼:
<h1><%= @job.category %></h1>
<p><%= @job.poster %></p>
<p><%= @job.location %></p>
<p><%= @job.description %></p>
<%= link_to "Home", root_path %>
和它工作得很好。
這是我的形式分:
<%= simple_form_for(@job, html: {class: 'form-horizontal'}) do |f| %>
<div class="control-group">
<%= f.label "Poster:", class: 'control-label' %>
<div class="controls">
<%= f.select(:poster, options_for_select([['Nick Maloney','Nick Maloney'],
['Peter Brown','Peter Brown'],['Jen Morris','Jen Morris']])) %>
</div>
</div>
<div class="control-group">
<%= f.label "Category:", class: 'control-label' %>
<div class="controls">
<%= f.select(:category, options_for_select([['Landscaping','Landscaping'],
['Babysitting','Babysitting'],['Tree planting','Tree planting']])) %>
</div>
</div>
<div class="control-group">
<%= f.label "Location:", class: 'control-label' %>
<div class="controls">
<%= f.select(:location, options_for_select([['Dorchester','Dorchester'],
['Roxbury','Roxbury'],['Mattapan','Mattapan']])) %>
</div>
</div>
<div class="control-group">
<%= f.label "Status:", class: 'control-label' %>
<div class="controls">
<%= f.select(:status, options_for_select([['New','New'],
['Pending','Pending'],['Complete','Complete']])) %>
</div>
</div>
<%= f.input :description, label: "Job Description" %>
<%= f.submit 'Add Job', class: 'btn btn-default' %>
<% end %>
,這是我jobs_controller.rb:
class JobsController < ApplicationController
before_action :find_job, only: [:show, :edit, :update, :destroy]
def index
@jobs = Job.all.order("created_at DESC")
end
def show
end
def new
@job = Job.new
end
def create
@job = Job.new(jobs_params)
if @job.save
redirect_to @job, notice: 'Your job was successfully added'
else
render "New"
end
end
def edit
end
def update
end
def destroy
end
private
def jobs_params
params.require(:job).permit(:poster, :category, :location, :status, :description)
end
def find_job
@job = Job.find(params[:id])
end
end