我对视图中的路径有一个问题,我不知道如何解决。我的"类别" that has_many"帖子"one_answers"属于"类别"的帖子。
1.-我想在主页上显示特定类别的最后一篇文章(ID编号" 1")。然后,我希望该帖子链接到显示帖子路径,但我会收到此错误:
"不知道的动作在scontroller中找不到动作"索引"
我认为我的道路错误是因为我不需要索引视图,因为我只会显示该特定的帖子。因此,我认为category_posts_path(@last_post)不是正确的路径(我不知道在哪里寻找有关在视图中制作路由路径的更多信息...)。实际上,浏览器向我展示了当它是" 1"类别的帖子时正在寻找" 2"类别...?我究竟做错了什么?这是浏览器路线:
http://localhost:3000/en/categories/2/posts
这是我的视图/类别/home.html.erb文件:
<div class="post_details">
<h2><%= @last_post.title %></h2>
<%= image_tag @last_post.image(:header), class: "post_image" %>
<p><%= truncate @last_post.body, length: 100 %></p>
<p class="button"><%= link_to "READ MORE", category_posts_path(@last_post) %></p>
</div>
2.-我在视图/类别/show.html.erb文件中有另一个路径问题。我有一个循环显示一个特定类别的所有帖子,但是当我在某个帖子中链接(显示)时,再次出现"索引"错误:
"不知道的动作在scontroller中找不到动作"索引"
这是浏览器路由:
http://localhost:3000/en/categories/1/posts
这是视图/类别/show.html.erb文件:
<div class="post_details">
<h2><%= link_to post.title, category_posts_path(post) %></h2>
<%= image_tag post.image(:header), class: "post_image" %>
<p><%= post.body %></p>
</div>
这是categories_controller.rb文件:
class CategoriesController < ApplicationController
before_action :get_categories
def index
end
def show
@category = Category.find(params[:id])
end
def home
if params[:set_locale]
redirect_to root_url(locale: params[:set_locale])
else
@category = Category.find_by_id(1)
@last_post = @category.posts.order("created_at desc").first
end
end
def get_categories
@categories = Category.all.order("rank asc, name asc")
end
end
这是我的posts_controller.rb文件:
class PostsController < ApplicationController
def show
@category = Category.find(params[:category_id])
@post = @category.posts.find(params[:id])
end
end
这是我的路线。RB文件:
scope '(:locale)' do
resources :categories do
resources :posts
end
resources :contacts
root 'categories#home'
get "/contact" => "contacts#new"
# static pages
get "/investment" => "contents#investment"
get "/partner-with-us" => "contents#partner", as: "partner"
get "/our-companies" => "contents#companies", as: "companies"
get "/site-map" => "contents#sitemap", as: "sitemap"
get "/terms-and-conditions" => "contents#terms", as: "terms"
get "/privacy" => "contents#privacy"
end
当您嵌套路线时,您应该始终考虑在给定路线中的父母和孩子。由于您的路径对您的关联一无所知,因此您必须明确定义嵌套中的每个对象。
即。由于您在链接到给定类别的最后一篇文章的类别中嵌套了帖子,看起来像这样: category_post_path(@category, @last_post)
(我认为您也有一个错别字-category_posts_paths
-链接到帖子索引索引 - 因此错误。因此,请使用category_post_path.
,并同时给它父母类别和帖子。
您可以运行rake routes
以查看路径上的确切信息(或转到http://localhost:3000/rails/info/routes
)