1
我有一个Rails应用程序设置为API,另一个应用程序用于测试API。在测试应用程序中,我希望用户能够创建存储在API中的新的Household对象。现在,当我完成家庭表单并提交时,API中会创建一个新的Household对象,但不包含“名称”参数。它只是创建一个带有“created_at”和“updated_at”字段的新记录。如果有人能告诉我我做错了什么,我将不胜感激。这里是我的代码:使用form_tag将参数传递给API
在测试程序:
户/ 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中:
families_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
末
如果在提交表单时在你的'create'动作中输出'params [:household]',结果是什么?我敢打赌,“参数[:家庭]”是零。如果您的表单名称中出现这种情况,您的字段就像这样:<%= text_field_tag'household [name]'%>' – cristian
您是否检查了两端发送和接收的参数? – Phil