Rails URL行为

时间:2016-03-17 12:45:29

标签: ruby-on-rails

我有两个模型:ArticleComment

Article has_many Comments

当我访问comments#showarticles/1/comments/2时,我可以访问不属于该文章的评论。

例如,在这种情况下,ID为2的comment不属于ID为1的article,但我仍然可以访问此网址。

知道为什么吗?

2 个答案:

答案 0 :(得分:2)

当您嵌套URL时,您正在推断子资源属于父资源,并且应该限定它。

除非您强制执行此范围设定,否则您也可以不使用嵌套网址。嵌套URL使得public String DateInViewModel { get { return _dateInViewModel.ToString("MM/dd/yyyy hh:mm:ss"); } set { //You can use TryParseExact to avoid format error exception _dateInViewModel = DateTime.ParseExact(value, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture); OnPropertyChanged(new PropertyChangedEventArgs("DateInViewModel")); } } 在评论控制器的参数中可用。

假设您想要显示一条评论。

article_id

在回复下面的评论时,您通常希望此操作失败。在生产中,缺少的资源会响应404响应代码(找不到页面)。

如果您确实需要手动错误处理,可以执行以下操作:

def CommentsController < ActionController::Base
  def show
    @article = Article.find(params[:article_id])
    @comment = @article.comments.find(params[:id])
  end
end

注意我正在使用find_by,如果找不到文章资源(而不是find),则不会引发错误。

否则,如果您想使用find,则需要解除生成的def CommentsController < ActionController::Base before_action :set_article_or_redirect_to_root def show @comment = @article.comments.find(params[:id]) end private def set_article_or_redirect_to_root @article = Article.find_by(params[:article_id]) redirect_to root_path unless @article end end 错误(例如,您可能希望在日志中记录错误)。

ActiveRecord::RecordNotFound

答案 1 :(得分:1)

您可以在控制器中执行以下操作:

@comment = @article.comments.find(params[:comment_id])