Please help me solve the problem.

There is a controller:

class NewsController < ApplicationController def index # @news = News.all.order(created_at: :desc) @news = News.page(params[:page]) end def show end end 

I'm trying to generate a link like:

 <%= link_to 'More', controller: "news", action: "show", id: news_item.id %> 

but multiline. To do this, create the following template:

 <% @news .each do |news_item| %> <%= link_to(news_path, { controller: "news", action: "show", id: news_item.id }) do %> <span>qwerty</span> <% end %> <% end %> 

As a result, I get the following error message:

 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> 

1 answer 1

"undefined local variable or method 'news_path'" - ​​You have 'news_path' not exist. I think that means the way to the news, so you should check your routes. Dig routes.rb and the 'rake routes' command.

PS: The link can be shorter to write: link_to('text', news_path(news_item))

ZZY: Note that the English word news does not have a plural form (more precisely the opposite), then the link to the index page will be: news_index_path()

  • news_path exists because such a link works: <% = link_to 'More', controller: "news", action: "show", id: news_item.id%> In short, I do not need to write down the link, I need to enclose the block in it code (large). - cyklop77
  • news_path does not exist. This is what the interpreter says to you! Take the dictionary and translate: "undefined local variable or method 'news_path'" news_path (), if we are talking about an assistant from the router, this is a wrapper for calling url_for ({controller: "news", action: "show", id: news_item. id}), since you are passing the hash, the news_path is not used in your variant. - mayar
  • you're right. thank you very much - cyklop77