On one tutorial, I know some link_to code like this.
lists/index.html.erb
<ul class="lists box">
<% lists.each do |list| %>
<li>
<h2 class="list_title">
<%= link_to list.title, list %>
</h2>
<p>
<%= truncate(list.content, length: 99) %>
<br>
<%= link_to list.node.name, list.node, class: "node" %>
</p>
</li>
<% end %>
</ul>
and 2 tables
create_table "lists", force: :cascade do |t|
t.string "title"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "node_id"
end
create_table "nodes", force: :cascade do |t|
t.string "name"
t.string "summary"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
2 models
class Node < ActiveRecord::Base
has_many :lists
end
class List < ActiveRecord::Base
belongs_to :node
end
controllers is also OK
class ListsController < ApplicationController
before_action :set_list, only: [:show, :edit, :update, :destroy]
def index
@lists = List.all.order(created_at: :desc).page(params[:page]).per(15)
end
def show
@list = List.find(params[:id])
end
.
.
.
private
def set_list
@list = List.find(params[:id])
end
def list_params
params.require(:list).permit(:title, :content)
end
end
another controller
class NodesController < ApplicationController
before_action :set_node, only: [:show, :edit, :update, :destroy, :node_list]
def index
@nodes = Node.all
end
def show
@node = Node.find(params[:id])
end
.
.
.
.
my routes
Rails.application.routes.draw do
resources :lists, only: [:index, :show, :new]
devise_for :users
resources :users
resources :nodes, only: [:show]
root 'lists#index'
end
When I rails s , I got error
NoMethodError in Lists#index
Showing /Users/zhangxiaodong/workspace/listlist/app/views/lists/_list_list.html.erb where line #10 raised:
undefined method `name' for nil:NilClass
and when I change the link_to
<%= link_to list.node.name, list.node, class: "node" %>
to <%= link_to "list.node.name", list.node, class: "node" %>
The page is no error ,but the node.name link loop not on the page.
I look API link_to [http://api.rubyonrails.org/] ,no work, can you tell me how loop my node .
lists/index.html.erb
should look like the following:
<ul class="lists box">
<% lists.each do |list| %>
<li>
<h2 class="list_title">
<%= link_to list.title, list_path(list) %>
</h2>
<p>
<%= truncate(list.content, length: 99) %>
<br>
<%= link_to list.node.name, node_path(list.node), class: "node" if list.node.present? %>
</p>
</li>
<% end %>
</ul>