Reputation: 343
I have a rails app set up as an API and another app I am using to test the API. In the test app I want the user to be able to create a new Household object which is stored in the API. Right now, when I complete the household form and submit, a new Household object is created in the API, but the "name" param is not being included. It just creates a new record with "created_at" and "updated_at" fields only. If anyone can tell me what I am doing wrong, I would appreciate it. Here is my code:
In the test app:
households/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
And in the 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
end
Upvotes: 1
Views: 1016
Reputation: 8744
In order for your app to submit the correct params do this (look at how I named the input):
<%= form_tag households_path, :method => :post do %>
Name: <%=text_field_tag 'household[name]' %><br />
<%=submit_tag 'Save' %>
<%end%>
or instead of form_tag use form_for
<%= form_for Household.new do |f| %>
First name: <%= f.text_field :name %><br />
<%= f.submit 'Save' %>
<% end %>
If you want to check what is wrong with the way the app is right now, in your browser open the web inspector and look how your input is named (is just name and not household['name'] as you expect it on the server)
You can check it on the server too, by doing this:
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
To avoid invalid database entries validate your household:
class HouseHold < ActiveRecord::Base
validate :name, presence: true
end
Upvotes: 2