我正在努力学习如何使用“Ancestry”宝石。我在Railscast中观看了相关剧集并获取了代码。 message
表工作正常。但我正在尝试使用名为locations
的新表复制它。我已复制并更改了所有代码的名称(我相信)。
我创建了第一个位置。但是,当我转到localhost:3000/locations
时,我会为NilClass获取undefined method
model_name':类for
_ form.html.erb`行:
<%= form_for @location do |f| %>
routes.rb
:
Messenger::Application.routes.draw do
resources :locations
resources :messages
root :to => 'messages#index'
end
_form.html.erb
:
<%= form_for @location do |f| %>
<%= f.error_messages %>
<%= f.hidden_field :parent_id %>
<p>
<%= f.label :locname, "New Location" %><br />
<%= f.text_area :locname, :rows => 8 %>
</p>
<p><%= f.submit "Post Location" %></p>
<% end %>
index.html.erb
:
<% title "Locations" %>
<%= nested_locations @locations.arrange(:order => :created_at) %>
<%= render "form" %>
locations_controller.rb
:
class LocationsController < ApplicationController
def index
@locations = Location.scoped
@location = Location.new
end
def show
@location = Location.find(params[:id])
end
def new
@location = Location.new(:parent_id => params[:parent_id])
end
def create
@location = Location.new(params[:location])
if @location.save
redirect_to locations_url
else
render :new
end
end
def destroy
@location = Location.find(params[:id])
@location.destroy
redirect_to locations_url
end
端
locations_helper.rb
:
module LocationsHelper
def nested_locations(locations)
locations.map do |location, sub_locations|
render(location) + content_tag(:div, nested_locations(sub_locations), :class => "nested_locations")
end.join.html_safe
end
end