我对编程和轨道相对较新,所以请放纵:)
我正在为自己建立一个包含博客的网站。我有两个嵌套的模型,我似乎不明白如何使用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
articles_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'%>
答案 0 :(得分:3)
您是否尝试使用指出问题的地方?
render 'articles/show'
您不需要使用article_comment_path
,因为这是一条完整路径,而不仅仅是存储视图模板的地方。在这种情况下,您只需要视图。您必须确保获得在此视图中使用的所有实例变量。
更新:
@article = Articles.find(article_id)
render 'articles/show'