使用form_tag将参数传递给API

时间:2015-01-16 16:01:30

标签: ruby-on-rails

我有一个rails应用程序设置为API和另一个我用来测试API的应用程序。在测试应用程序中,我希望用户能够创建存储在API中的新的Household对象。现在,当我完成家庭表单并提交时,API中会创建一个新的Household对象,但不会包含“name”参数。它只是创建一个仅包含“created_at”和“updated_at”字段的新记录。如果有人能告诉我我做错了什么,我将不胜感激。这是我的代码:

在测试应用中:

户/ new.html.erb:

<%= form_tag households_path, :method => :post do %>
Name: <%=text_field_tag :name %><br />
<%=submit_tag 'Save' %>
<%end%>

households_controller.rb:

def create
  uri = "#{API_BASE_URL}/households.json"
  payload = params.to_json
  rest_resource = RestClient::Resource.new(uri)
  begin
    rest_resource.post payload, :content_type => 'application/json'
    redirect_to households_path
  rescue Exception => e
    redirect_to households_path
  end
end

在API中:

households_controller.rb

def create
@household = Household.new(params[:household])

if @household.save
  render json: @household, status: :created, location: @household
else
  render json: @household.errors, status: :unprocessable_entity
end

1 个答案:

答案 0 :(得分:2)

为了让您的应用提交正确的参数,请执行此操作(查看我如何命名输入):

<%= form_tag households_path, :method => :post do %>
  Name: <%=text_field_tag 'household[name]' %><br />
  <%=submit_tag 'Save' %>
<%end%>

或代替form_tag使用form_for

<%= form_for Household.new do |f| %>
  First name: <%= f.text_field :name %><br />
  <%= f.submit 'Save' %>
<% end %>

如果您想检查应用程序现在的方式有什么问题,请在浏览器中打开Web检查器,查看您的输入是如何命名的(只是名称而不是家庭[&#39;名称&#39; ]正如你在服务器上所期望的那样)

您也可以在服务器上查看它:

def create
  @household = Household.new(params[:household])
  puts "params[:household] = #{params[:household]}" # this will be nil
  puts "params[:name] = #{params[:name]}" #this will display what you have typed inside your input
  ...
end

为避免无效的数据库条目验证您的家庭:

class HouseHold < ActiveRecord::Base
  validate :name, presence: true
end