Rails two related models in one form not saving - ruby-on-rails-3

My form fields are:
<%= form_tag signup_path, :class=>"no-ajax form-signin" do %>
<fieldset>
<legend>Company</legend>
<div class="field">
<label>Company Name</label>
<%= text_field :company, :name, :class => "input-block-level" %>
</div>
<%= hidden_field :company, :accounttype_id, :value => 2 %>
</fieldset>
<fieldset>
<legend>User</legend>
<div class="field">
<label>First Name</label>
<%= text_field :user, :first_name, :class => "input-block-level" %>
</div>
<div class="field">
<label>Last Name</label>
<%= text_field :user, :last_name, :class => "input-block-level" %>
</div>
<div class="field">
<label>Email</label>
<%= text_field :user, :email, :class => "input-block-level" %>
</div>
<div class="field">
<label>Role</label>
<%= text_field :user, :role_id, :value => 2 %>
</div>
</fieldset>
<fieldset>
<div class="field">
<label>Password</label>
<%= text_field :user, :password, :class => "input-block-level" %>
</div>
<div class="field">
<label>Confirm Password</label>
<%= text_field :user, :password_confirmation, :class => "input-block-level" %>
</div>
</fieldset>
<div class="form-actions">
<%= submit_tag 'Sign Up', :class => "btn btn-large btn-success btn-block" %>
</div>
<% end %>
My controller for the form is:
def signup
#company = Company.new
#user = #company.users.build
if #company.save
redirect_to :action => 'success'
else
render :action => 'signup'
end
end
When I save, it says that it fails.
This is the data that was posted (pasted from the rails console):
{"utf8"=>"✓", "authenticity_token"=>"9y4JeSvm34P05FBKbP3D3aToHlwejFZBkSyPbmGMJrk=", "company"=>{"name"=>"Test Co", "accounttype_id"=>"2"}, "user"=>{"first_name"=>"Andy", "last_name"=>"Bernard", "email"=>"andy#testco.com", "role_id"=>"2", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}
What is the form unable to save
is there a better way to do this process? (create new Company, then create user linked to that company, all in one form)

The signup action in your controller does not save #company because no attributes were passed when Company.new was called.
#company = Company.new(params[:company])
will pass the parameters "company"=>{"name"=>"Test Co", "accounttype_id"=>"2"}.
Likewise for "user"=>{...}:
#user = #company.users.build(params[:user])
For an all-in-one form, Rails provides the following method accepts_nested_attributes_for which allows you to create both the company and the user in one go.

Related

Routing Error No route matches [POST]"/contacts/new

I seem to be stuck on a Ruby on Rails tutorial. I keep getting the error that is in the title of this post, which is:
Routing Error No route matches[POST]"/contacts/new"
app/views/contacts/new.html.erb
<div class="container">
<div class="rpw">
<h3 class="text-center">Contact Us</h3>
<div class="col-md-4 col-md-offset-4">
<%= flash[:notice] %>
<div class="well">
<%= form_for "/contacts" do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.text_field :email, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :comments %>
<%= f.text_area :comments, class: 'form-control' %>
</div>
<%= f.submit 'Submit', class: 'btn btn-success' %>
<% end %>
</div>
</div>
</div>
routes.rb
Rails.application.routes.draw do
root to: 'pages#home'
get 'about', to: 'pages#about'
resources :contacts
end
contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(contact_params)
if #contact.save
redirect_to new_contact_path, notice: "Message sent."
else
redirect_to new_contact_path, notice: "Error occured"
end
end
private
def contact_params
params.require(:contact).permit(:name, :email, :comments)
end
end
contact.rb
class Contact < ActiveRecord::Base
end
I am unsure where I am going wrong. Please help me. I have been trying to fix this for a few days now.
In new.html.erb
try changing
<%= form_for "/contacts" do |f| %>
to
<%= form_for #contact do |f| %>

Why am I getting undefined method `model_name' for NilClass:Class?

I get this when I visit a user's profile page. so localhost:3000/users/1 for example...
I get it here in line 1
1: <%= form_for(#micropost) do |f| %>
2: <%= render 'shared/error_messages', object: f.object %>
3: <div class="field no-indent">
4: <%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
so then I have two micropost forms one is here
<%= form_for(#micropost, :html => { :id => "sale" }) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
and another one is here
<%= form_for(#micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "purchase" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
Here is my routes.
SampleApp::Application.routes.draw do
resources :users do
resources :comments
member do
get :following, :followers
end
end
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy] do
resources :comments
resources :kind
end
resources :relationships, only: [:create, :destroy]
root to: 'static_pages#home'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
and here is the code for the page itself (users show)
<section>
<%= render 'shared/user_info' %>
</section>
<section>
<div id= "purchases">
<%= render 'shared/micropost_form_purchase' %>
</div>
<div id="sales">
<%= render 'shared/micropost_form_sale' %>
</div>
</section>
<% provide(:title, #user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for #user %>
<%= #user.name %>
</h1>
</section>
</aside>
<div class="span8">
<% if #user.microposts.any? %>
<h3>Purchases I am interested in (<%= #user.microposts.count %>)</h3>
<ol class="microposts">
<%= render #microposts %>
</ol>
<%= will_paginate #microposts %>
<% end %>
</div>
</div>
also I dont understand how you can pass an empty object into form for? Isn't the whole point of the form to create the object?
According to the article which I stumbled upon today it may be that the object you are passing to form_for (#micropost in this case) is nil or empty.
Here's the mentioned article: http://schneems.com/post/31460949407/raise-hell-better-programming-through-error-messages

PUT routes broken by scope

In my application, I have several resources scoped into 'admin' as follows (in routes.rb):
scope 'admin', :as => 'admin' do
resources :events
end
So when I go in to use the #new or #update methods through the form, I end up getting the ActionController exception saying No route matches [PUT] "/admin/events".
rake routes produces the following:
admin_events GET /admin/events(.:format) events#index
POST /admin/events(.:format) events#create
new_admin_event GET /admin/events/new(.:format) events#new
edit_admin_event GET /admin/events/:id/edit(.:format) events#edit
admin_event GET /admin/events/:id(.:format) events#show
PUT /admin/events/:id(.:format) events#update
DELETE /admin/events/:id(.:format) events#destroy
_form code:
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<%= form_for #event, :html => { :class => 'form-horizontal' }, :url => url_for(:controller => 'events', :action => 'index') do |f| %>
<fieldset>
<div class="control-group">
<%= f.label :name, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :name %>
</div>
</div>
<div class="control-group">
<%= f.label :event_date, :class => 'control-label' %>
<div class="controls date-selects">
<%= f.datetime_select :event_date, :start_year => 2012 %>
</div>
</div>
<div class="control-group">
<%= f.label :publish_date, :class => 'control-label' %>
<div class="controls date-selects">
<%= f.datetime_select :publish_date, :start_year => 2012 %>
</div>
</div>
<div class="control-group">
<%= f.label :blurb, :class => 'control-label' %>
<div class="controls">
<%= f.text_area :blurb, :class => 'span6 wysi' %>
</div>
</div>
<div class="control-group">
<%= f.label :graphic, :class => 'control-label' %>
<div class="controls">
<%= f.file_field :graphic %>
</div>
</div>
<div class="control-group">
<%= f.label :tix_link, :class => 'control-label' %>
<div class="controls">
<%= f.url_field :tix_link %>
</div>
</div>
<div class="form-actions">
<%= f.submit 'Submit', :class => 'btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")), admin_events_path, :class => 'btn' %>
</div>
</fieldset>
<% end %>
What am I doing wrong?
Try changing your form tag from:
<%= form_for #event, :html => { :class => 'form-horizontal' }, :url => url_for(:controller => 'events', :action => 'index') do |f| %>
to:
<%= form_for [:admin, #event], :html => { :class => 'form-horizontal' } do |f| %>
This will use the proper admin scope and properly generate the url, depending if the #event is persisted on the database or not.

Rails 3 Nested Attributes

I've had this issue for a few days and looked over every tutorial and stack overflow. I cannot seem to resolve. I can't seem to use nested attributes that work. I get an error with this form view.
**Form View**
<%= form_for #trip, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
<%= f.label :start, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :start, :class => 'text_field' %>
</div>
<div class="control-group">
<%= f.label :end, :class => 'control-label' %>
<div class="controls">
<%= f.text_field :end, :class => 'text_field' %>
</div>
<div class="control-group">
<% f.fields_for :driver do |d| -%>
<%= d.label :driver, :class => 'control-label' %>
<div class="controls">
<%= d.text_field :driver, :class => 'text_field' %>
</div>
Model:
class Trip < ActiveRecord::Base
attr_accessible :end, :start
belongs_to :driver
belongs_to :customer
accepts_nested_attributes_for :driver
end
class Driver < ActiveRecord::Base
attr_accessible :name
has_many :trips
end
As you said you need closing end tag.
If you have the "Can't mass-assing procteted attributes: drivers" error you must declare "attr_accessible" on :drivers_attributes at the trip model.

form_for not rendering to view but is generating html correctly

I have the following form in my view:
<%= form_for #new_home, :url => {:controller => "homes", :action => "create"} do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.label :name, "Home Name:" %><br />
<%= f.text_field(:name) %>
<%= f.submit("Add New Home", :class => "green_button") %>
<% end %>
And controller:
def main
#new_home = Home.new
end
The generated html is:
<form accept-charset="UTF-8" action="/homes/create" class="new_home" id="new_home" method="post"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="lyvJq8FmFoOvzi7LYNhkrY8t9WI9phtBlNdGvMOFoF8=" />
<input id="home_user_id" name="home[user_id]" type="hidden" value="1" />
<label for="home_name">Home Name:</label><br />
<input id="home_name" name="home[name]" size="30" type="text" />
<input class="green_button" name="commit" type="submit" value="Add New Home" />
</form>
For some reason i cannot see the form being displayed in my view. There is no error generated. All i see is a blank page with no form. I have not applied any jquery or css to hide the form. Any thoughts?
I think you are missing the div field and action classes. See below.
<%= form_for #new_home, :url => {:controller => "homes", :action => "create"} do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="field">
<%= f.label :name, "Home Name:" %><br />
<%= f.text_field :name %>
</div>
<div class="action">
<%= f.submit("Add New Home", :class => "green_button") %>
</div>
<% end %>
Let me know if it doesn't work!