【问题标题】:redirect_to category_post_path(@post)重定向到 category_post_path(@post)
【发布时间】:2013-11-20 16:28:53
【问题描述】:

我有帖子和帖子类别 帖子属于_to:类别 类别 has_many :posts 我想在创建新帖子时将我重定向到创建的帖子 但是当我在 Posts 控制器中使用时

def create
        @category = Category.find(params[:category_id])
        @post =  current_user.posts.build(post_params)
        if @post.save
      flash[:success] = "Поздравляем Ваше задание опубликованно"
      redirect_to category_post_path(@post) 
  else
    render 'new'
  end
    end

这个

redirect_to category_post_path(@post)

rails 给我错误

没有路由匹配 {:action=>"show", :controller=>"posts", :category_id=>#, :id=>nil, :format=>nil} 缺少必需的键:[:id]

但我想要@post.save rails redirect_to 创建帖子

请帮忙。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    我敢打赌你的路线是这样的:

    resources :categories do
      resources :posts
    end
    

    这会创建 URL 帮助器 category_post_path,但它需要一个类别和一个帖子。

    试试这个:

    category_post_path @category, @post
    

    【讨论】:

    • 对不起菜鸟,但现在 Rails 在 PostsController 中给出错误 ArgumentError#show wrong number of arguments (1 for 0) def show @posts = Post.find(params(:id))
    • 你的问题是params(:id) 应该是params[:id]。注意方括号。整行:@posts = Post.find(params[:id])。如果你想解释一下:params是一个返回哈希的方法,所以params[:id]调用params方法,返回一个哈希,然后检索索引:id的值。
    猜你喜欢
    • 1970-01-01
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 2014-06-20
    • 2017-06-19
    相关资源
    最近更新 更多