请帮助解决问题。
有一个控制器:
class NewsController < ApplicationController
def index
#@news = News.all.order(created_at: :desc)
@news = News.page(params[:page])
end
def show
end
end
我正在尝试创建一个类似的链接:
<%= link_to 'More', controller: "news", action: "show", id: news_item.id %>
但多线。为此,请创建以下模板:
<% @news.each do |news_item| %>
<%= link_to(news_path, { controller: "news", action: "show", id: news_item.id }) do %>
<span>qwerty</span>
<% end %>
<% end %>
结果是以下错误消息:
NameError in News#index
Showing /home/kalinin/rails/visit/app/views/news/index.html.erb where line #4 raised:
undefined local variable or method `news_path' for #<#<Class:0x007f221c8a0738>:0x007f221c391dc8>
rake routes:
..............
.........
news_index GET /news/index(.:format) news#index
news_show GET /news/show(.:format) news#show
............
..........
答案 0 :(得分:1)
尝试这样: -
<% @news.each do |news_item| %>
<%= link_to "Qwerty", news_show_path(id: news_item.id) %>
<% end %>
答案 1 :(得分:0)
使用rake路由并检查news_path路由是否存在。另外link_to函数的第一个参数应该是link的名称。
答案 2 :(得分:0)
还可以阅读有关路由的Rails指南。 我认为你有一个概念上的误解,即快速阅读可能有所帮助。
从这里开始:)
http://guides.rubyonrails.org/routing.html#generating-paths-and-urls-from-code
答案 3 :(得分:-1)
<% @news.each do |news_item| %>
<%= link_to(url_for({controller: "news", action: "show", id: news_item.id})) do %>
<div>
<span>title:</span>
<span><%= news_item.title %></span>
</div>
<div>
<span>Date:</span>
<span><%= news_item.created_at.to_s(:ru_datetime_for_news) %></span>
</div>
<% end %>
<%= link_to 'More', controller: "news", action: "show", id: news_item.id %>
<br>
<br>
<br>
<% end %>