简体   繁体   中英

How to link to create action using link_to tag in rails

I tried to link to create action, and thought something like

    <%= link_to "Create new user", {controller: 'users' , action: 'create'}, method: 'post'  %>

, but when I click the generated link nothing happens and the url changes to

    http://0.0.0.0:3000/users?method=POST+%2Fusers

which indicates that the request is handled as a GET request and not a POST, any ideas ?

here is the create action from the users controller

        def create


        @user = User.new params[:user]

        if @user.save
            flash[:notice] = 'User has successfully been created.'
            redirect_to users_path
        else
            flash[:notice] = 'There was an error creating this user.'
            redirect_to :back
        end

end 

在rails中: <%= link_to 'Create new user' , new_user_path %> ,请查阅文档以获取有关路由的更多信息。

尝试使用(未经测试):

<%= link_to "Create new user", {controller: 'users' , action: 'create', method: 'post'}  %>

You should use the named paths as they are generated from your routes.

<%= link_to "Create new user", users_path, method: "post" %>

You can find the names of these methods by running rake routes and looking at the first column. Append _path for local links and _url for full URLs.

More on named routes here

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