weixin_33699914 2016-01-26 18:22 采纳率: 0%
浏览 33

用Rails填充api数据

Just coded a rails 4 application contains a simple form that create a product on submit.

before user submit and save the product to the database I would like to add a small verification that call an external API that receive as parameters the client side form fields and display its output to the web page using ajax.

current behaviour is that it saves the product and just after it shows the API data after the whole page refreshes.

the expected is that not all page refreshes but just the API results (tax partial) and when click again a different submit button it will submit the form finally.. I would appreciate any thoughts to implement it,

_form.html.erb

<%= form_for @product, remote: true do |f| %>
 <%= f.text_field :name, placeholder: :name %>
  <% unless @product.id.nil?
     @product.taxes_from_api.each do |t| %>
       <%= render "tax", :f => t %>
  <% end %>
 <%= f.submit %>
<%= end %>

products_controller.rb:

def create
 @product = Product.new(product_params)
 respond_to do |format|
  if @product.save
    format.html 
  else
    format.html { render action: 'new' }
    format.json { render json: @product.errors, status: :unprocessable_entity }
    format.js   { render json: @product.errors, status: :unprocessable_entity }
  end
 end
end

product.rb:

  def taxes_from_api
    API:get_taxes(product.name) # not really important 
  end
  • 写回答

1条回答 默认 最新

  • weixin_33749242 2016-01-26 18:33
    关注

    I like that you started with a working solution and are asking help for an improvement, rather than ask for the whole thing. I don't want to code the solution for you, but I'll give you a few pointers:

    1. Create a Taxes controller with a create action (to keep it RESTful) that responds with Javascript. See more about it on the Rails Guides

    2. Create a form that submits to that new action (taxes#create) with format: :json. That form has a text field for the product name and a submit button.

    3. Create a second form with two hidden fields (product_name, taxes) and a hidden submit button. This form will submit to products#create

    4. Let the user fill the product name and submit the first form. On success, using Javascript:

      1. Copy the product name from one form to the other.
      2. Fill the taxes on the second form.
      3. Hide the submit button for the first form.
      4. Show the submit button for the second
    5. The user can submit the new form containing both the product name and the calculated taxes.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘