How to post html form data to controller using rub

2020-08-04 04:40发布

问题:

I am using ruby on rails 3.1. And am trying to post html form data to controller for saving the record in database. But I am getting routing error like this 'No route matches [POST] first/save' .But when I tried to run this link in address bar like '127.0.0.1:3000/first/save' it is working fine. Can any one please tell me where am doing wrong.

My routes are like:

Rails.application.routes.draw do 

  root 'first#hello'


  get 'first/save'

end

And my html form is like:

    <form accept-charset="UTF-8" method='post' action='/first/save'>

        <label for='S.No'>S.No</label> 
            <input type="text" name="s_no" placeholder='Enter s. no.'> 
        <label for='name'>Name</label>
            <input type="text" name='name' placeholder='Enter your name'> <br>
        <label for='seller_id'>Seller ID</label>
            <input type="text" name='seller_id' placeholder='Enter your seller ID'> <br>
        <label for='email'>Email</label>
            <input type="email" name='email' placeholder='Enter your email'> <br>
        <label for='img_url'>Image</label>
            <input type='text' name='img_url' placeholder='Enter your image url'> <br>
            <input type="submit" name='save' value='Save'>
    </form>

And here is my controller:

class FirstController < ApplicationController

  def save
    @name = params[:name]
    @email = params[:email]
    @seller_id = params[:seller_id]
    @img_url = params[:img_url]
    @s_no = params[:s_no]
  end
end

回答1:

If you want to do POST requests, instead of

get 'first/save'

you should have

post 'first/save'