繁体   English   中英

Rails-与Rails嵌套时的布线-初学者

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM