简体   繁体   中英

Rails nested routes for devise user

Hello I have an issue with my routing. I currently have devise user with a nested post resource. Currently I am trying to be able to create a new post for each user.

routes.rb

Rails.application.routes.draw do

  root 'home#index'

  resources :dashboard

  devise_for :users, :path => '', :path_names => {
    :sign_in => 'login',
    :sign_out => 'logout',
    :sign_up => 'register'
  }

  resource :users do
    resources :posts
  end
end

posts_controller.rb

class PostsController < ApplicationController
  before_action :set_user

  def index
    @posts = @user.posts
  end

  def new
    @post = @user.posts.new
  end

  def create
    @post = @user.posts.new(post_params)
    if @post.save
      redirect_to :controller => 'dashboard', :action => 'index'
    else
      render :new
    end
  end

private

  def post_params

  end

  def set_user
    @user = current_user
  end
end

link

<%= button_to "New Post", new_users_post_path(current_user), :class => "btn btn-default navbar-btn", :method =>  :get  %>

route

   new_users_post GET    /users/posts/new(.:format)      posts#new

This leads to: NoMethodError at /users/posts/new undefined method `user_posts_path' for #<#:0x007fe01d1608f0>. Any ideas? Thanks!

It doesn't resolve problem, but new_users_post_path should be without any params:

<%= button_to "New Post", new_users_post_path, class: "btn btn-default navbar-btn", method:  :get  %>

also resource :user instead users

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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