如何发送参数rails表单



我知道这有点傻。无论如何,我想实现一个测试优惠券系统。其中,如果用户输入优惠券,则数据库中该优惠券的相应金额将被添加到该特定用户的账户中。
我有我的优惠券控制器作为

class CouponsController < ApplicationController
def redeem
    @coupon = Coupon.find_by_code(params[:code])
    if (@coupon.number_avail!=0)
      current_user.account = current_user.account + @coupon.amount
    else 
      flash[:notice] = "Coupon Invalid!"
      redirect_to root_path
    end
  end
end

我的路线文件为:

get '/coupon/redeem' => 'coupons#redeem'

一切都很好做手动喜欢网站/优惠券/兑换?代码=测试;这很有效。但我想接受用户的输入并传递参数。

我如何安排有一个表格,用户可以输入优惠券代码并将其传递给优惠券#兑换?

谢谢。

为了简单起见,只需添加一个

     redeem.html.erb   # in app/views/coupons
     #add this kind of code
      <form method="post" action="redeem" >
     <input type="text" value="" size="" name="coupon[yourchoice]" id="coupon_yourchoice">
        <%= button_to "submit" ,:action => "redeem" %>
      </form>
        #in your app/controller/coupon
           def redeem
             @variable = params
             puts @variable.inspect # to see the content
           end

    #for posting parameters to different url
     step :1  change the action of the form something like this,
     action="/yourchoice/abc"
         step :2  make changes in config/route.rb
       match '/yourchoice/abc', :to => 'yourcontroller#action', :via => [:get ,:post]
    step : 3  make an action in  yourcontroller
       def action
          @var = params
          p @var   #check the variable
       end

呃,这似乎很基本。

<% form_tag redeem_coupons_path do %>
  <label>Coupon <%= text_field_tag "code" %></label>
  <%= submit_tag "Submit" %>
<% end %>

请注意,此表单将使用POST请求,这是执行此操作的适当方法。您应该更改路由,使其期望POST而不是GET。

编辑:此外,您的控制器代码需要考虑到找不到该代码优惠券的可能性。我会把它改成这个:

def redeem
  if (@coupon = Coupon.find_by_code(params[:code])) && (@coupon.number_avail != 0)
    current_user.account = current_user.account + @coupon.amount
  else 
    flash[:notice] = "Coupon Invalid!"
    redirect_to root_path
  end
end

正确的方法是使用标准的资源路由:

#config/routes.rb
resources :coupons, only: [], param: :code do
   match :redeem, via: [:get, :post], on: :member #-> url.com/coupons/:code/redeem
end
#app/controllers/coupons_controller.rb
class CouponsController < ApplicationController
   def redeem
      @coupon = Coupon.find params[:code]
      if (@coupon.number_avail!=0)
         current_user.increment!(:account, @coupon.amount)
      else 
         redirect_to root_path, notice: "Coupon Invalid!"
      end
   end 
end

这将允许您使用:

<%= button_to @coupon.value, coupon_redeem_path(@coupon) %>

--

如果你想让用户指定优惠券代码本身,你可以保留上面的routescontroller#action,除了使用不同的输入:

<%= form_for coupon_redeem_path do %>
   <%= text_field_tag :code %>
   <%= submit_tag %>
<% end %>

如果你不想透露:coupon_id,你应该使用POST请求:

#config/routes.rb
resources :coupons, only: [], param: :code do
   post :redeem, on: :collection #-> url.com/coupons/redeem
end

GETPOST的区别在于。。。

在POST请求中,查询字符串(名称/值对)在HTTP消息体中发送

在GET请求中,查询字符串(名称/值对)在URL 中发送

最新更新