[英]Rails - routing when nesting with rails - beginner
我對編程和Rails比較陌生,所以請放縱:)
我正在為自己建立一個包含博客的網站。 我有兩個嵌套的模型,我似乎不太了解如何使用REST對我的文章和評論執行某些操作。
當我創建評論時,如果該評論未通過驗證,我希望它再次呈現頁面,以便用戶可以糾正他的錯誤並重新提交評論。 當我嘗試渲染時,它給了我一個缺少的模板錯誤。
這是代碼:
您還可以在github上找到此代碼-> https://github.com/MariusLucianPop/mariuslp-
routes.rb
Mariuslp::Application.routes.draw do
get "categories/new"
root :to => "static_pages#index"
match "login" => "visitors#login" # not rest
match "logout" =>"visitors#logout" # not rest
match "comment" => "articles#show"
resources :articles do
resources :comments
end
resources :tags, :taggings, :visitors, :categories, :comments
end
article_controller.rb
def show
@article = Article.find(params[:id])
@comment = @article.comments.new
end
comments_controller.rb
def create
article_id = params[:comment].delete(:article_id)
@comment = Comment.new(params[:comment])
@comment.article_id = article_id
if @comment.save
redirect_to article_path(@comment.article_id)
else
render article_path(@comment.article_id,@comment) ## This one doesn't work
end
end
def new
@comment = Comment.new
end
def destroy
Comment.find(params[:id]).destroy
redirect_to articles_path()
end
查看文章: _comment.html.erb
<div class="comment">
<%= comment.body %><br />
<%= link_to "Delete Comment", article_comment_path(@article), :method => :delete, :confirm => "Are you sure you want to delete this comment?" %>
</div>
_comment_form.html.erb
<%= form_for @comment do |f|%>
<%= f.hidden_field :article_id%>
<%= f.label :body %><br />
<%= f.text_area :body, :cols => 50, :rows => 6 %><br />
<%= f.submit%>
<%end%>
show.html.erb
<p><%= link_to "<< Back to Articles", articles_path%></p>
<div class = "article_show">
<%= label_tag :category_id %>
<%= @article.category_id%> <br />
<%= label_tag :title%>:
<%= @article.title%> <br />
<%= label_tag :body%>:
<%= @article.body%> <br />
<%= label_tag :tag_list%>:
<%= @article.tag_list%><br />
</div>
<br />
<% if session[:username]== "marius"%>
<div class ="admin">
<%= link_to "Edit", edit_article_path(@article)%>
<%= link_to "Delete", article_path(@article), :method => :delete, :confirm => "Are you sure you want to delete this article ?"%>
</div>
<%end%>
<br />
<%= render :partial => 'comment', :collection => @article.comments %>
<%= render :partial => 'comment_form'%>
您是否嘗試過使用指出問題的地方?
render 'articles/show'
您不需要使用article_comment_path
因為這是完整路徑,而不僅僅是存儲視圖模板的位置。 在這種情況下,您只需要視圖。 當然,您必須確保獲取在此視圖中使用的所有實例變量。
更新:
@article = Articles.find(article_id)
render 'articles/show'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.