0

我对编程和 Rails 比较陌生,所以请放纵:)

我正在为自己建立一个包含博客的网站。我有两个嵌套的模型,我似乎不明白如何使用 REST 对我的文章和评论执行某些操作。

当我创建评论时,如果评论没有通过验证,我希望它再次呈现页面,以便用户可以更正他的错误并重新提交评论。当我尝试渲染时,它给了我一个缺少模板的错误。

这是代码:

您也可以在 github 上找到此代码 --> https://github.com/MariusLucianPop/mariuslp-

路线.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

文章控制器.rb

def show
  @article = Article.find(params[:id])
  @comment = @article.comments.new
end

评论控制器.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%>

显示.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'%>
4

1 回答 1

3

您是否尝试过使用您指出问题的地方?

render 'articles/show'

您不需要使用article_comment_path,因为这是一个完整路径,而不仅仅是您存储视图模板的位置。在这种情况下,您只需要视图。当然,您必须确保获取您在此视图中使用的所有实例变量。

更新:

@article = Articles.find(article_id)
render 'articles/show'
于 2012-05-15T13:30:08.007 回答