Rails - Forms acting Weird: not saving any text_field - ruby-on-rails

After getting my question solved by Matteo Alessani in Rails - Id can't be found in Forms, I noticed that my form isn't saving the fields I pass.
I will copy here all the piece of code I have from the other question:
Routes:
resources :honors
Model:
class Honor < ActiveRecord::Base
belongs_to :person, :class_name => 'Person', :foreign_key => "person_id"
belongs_to :honored, :class_name => 'Person', :foreign_key => "honored_id"
belongs_to :group, :class_name => 'Group', :foreign_key => "group_id"
Controller:
def new
#person = Person.find(params[:person])
#honored = Person.find(params[:honored])
#group = Group.find(params[:group_id])
#honor = Honor.new
end
def create
#person = Person.find(current_person)
#honor = Honor.save(:group_id => params[:honor][:group],
:person_id => params[:honor][:person],
:honored_id => params[:honor][:honored])
if #honor.valid?
flash[:success] = "Honor created."
redirect_to (:back)
else
redirect_to (:back)
end
end
In the view:
<% #asked_groupmembership.each do |agm| %>
<%= link_to "Create Honor", new_honor_path(:group_id => #group.id,
:person => current_person.id, :honored => agm.member.id) %>
My Forms:
<% form_for #honor do |f| %>
<%= f.hidden_field :group_id, :value => #group.id %>
<%= f.hidden_field :person, :value => current_person.id %>
<%= f.hidden_field :honored, :value => #honored.id %>
<div class="field">
<%= f.label :texto %><br />
<%= f.text_field :texto %>
</div>
And the error is that I can get the ID's from group and person and the honored one, but nothing that I type in the forms (my attributes are in portuguese so I won't translate):
INSERT INTO "honors" ("group_id", "person_id", "honor_id", "texto", "nota",
"nivel_habilidade", "comprometimento", "tempo_demora",
"criatividade", "organicazao", "comunicacao", "trabalho_grupo", "created_at",
"updated_at") VALUES (39, 2, 44, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, '2011-05-26 12:58:56.433510', '2011-05-26 12:58:56.433510')
RETURNING "id".
Note: the Parameters in log are with the values.
Thanks!

You have mistake in controller
def create
#person = Person.find(current_person)
#honor = Honor.new(params[:honor])
if #honor.save
flash[:success] = "Honor created."
redirect_to (:back)
else
redirect_to (:back)
end
end

Related

Why do I get the error `undefined method 'map'`?

In my Ruby on Rails application I am trying to display a three drop down menus in the _form.html.erb which are rendered from the file _booking_lookup.html.erb and get there data from the drop down menu methods in the models.
_form.html.erb:
<%= render(:partial => '/booking_lookup', :locals=> {:film => #film = Film.all, :showings => #showings = Showing.all, :seats => #seats = Seat.all, :my_path => '/films/booking_lookup' }) %>
_booking_lookup.html.erb:
<%= form_tag my_path, :method=>'post', :multipart => true do %>
<%= select_tag ('title_id'),
options_from_collection_for_select(#films, :id, :title_info, 0 ),
:prompt => "Film" %>
<%= select_tag ('showings_id'),
options_from_collection_for_select(#showings, :id, :showing_times, 0 ),
:prompt => "Showings" %>
<%= select_tag ('seat_id'),
options_from_collection_for_select(#seats, :id, :seats_available, 0 ),
:prompt => "Seats" %>
<%= submit_tag 'Search' %>
film.rb:
class Film < ActiveRecord::Base
has_many :showings
belongs_to :certificate
belongs_to :category
def title_info
"#{title}"
end
end
seat.rb:
class Seat < ActiveRecord::Base
belongs_to :screen
has_many :bookings
def seats_available
"#{row_letter}#{row_number}"
end
end
showing.rb:
class Showing < ActiveRecord::Base
belongs_to :film
has_many :bookings
belongs_to :screen
def showing_times
"#{show_date.strftime("%e %b %Y")} # #{show_time.strftime("%H:%M")}"
end
end
But for some reason with the line: <%= select_tag ('title_id'),
options_from_collection_for_select(#films, :id, :title_info, 0 ),
:prompt => "Film" %> I get the error:
NoMethodError in Bookings#new
undefined method `map' for nil:NilClass
The weird part is that I am using a lot of this code else where, I have a _multi_search.html.erb form:
<%= form_tag my_path, :method=>'post', :multipart => true do %>
<!-- Genre: -->
Search By:
<%= select_tag ('cat_id'),
options_from_collection_for_select(#categories, :id, :category_info, 0 ),
:prompt => "Genre" %>
<%= select_tag ('cert_id'),
options_from_collection_for_select(#certificates, :id, :certificate_info, 0 ),
:prompt => "Age Rating" %>
<%= text_field_tag :search_string, nil, placeholder: "ACTOR" %>
or
<%= select_tag ('title_id'),
options_from_collection_for_select(#films, :id, :title_info, 0 ),
:prompt => "Film" %>
<%= submit_tag 'Search' %>
<% end %>
And is used in the application.html.erb:
<%= render(:partial => '/multi_search', :locals=> {:categories => #categories = existing_genres, :certificates => #certificates = Certificate.all, :films => #films = Film.all, :my_path => '/films/multi_find' }) %>
And that works fine.
What am I doing wrong?
It looks like #films is nil. Try setting #films = Film.all (instead of #film = Film.all) in _form.html.erb.
Update:
I would recommend moving the queries to the controller action. In the Model-View-Controller pattern, Controllers should be asking Models for data, not Views.
# BookingLookupController
def new
#films = Film.all
#showings = Showing.all
#seats = Seat.all
end
You can then reference the instance variables in the view.
<%= render partial: '/booking_lookup', locals: {films: #films, showings: #showings, seats: #seats, my_path: '/films/booking_lookup' } %>
In Controller, select fields as you just want to display names in dropdown
def method_name
#films = Film.select([:id, :title_info])
#showings = Showing.select([:id, :showing_times])
#seats = Seat.select([:id, :seats_available])
end
In page
<%= render(:partial => '/booking_lookup', :locals=> {:films => #films, :showings => #showings, :seats => #seats, :my_path => '/films/booking_lookup' }) %>
In partial
options_from_collection_for_select(films, :id, :title_info, 0 ),:prompt => "Film" %>

rails: exclude blank select_tag from url

I have a form on index.html.erb (User views):
<%= form_tag( '', :method => :get ) do %>
<% #company = Position.all.map { |p| [ p.company, p.company ] } %>
<%= select_tag "company", options_for_select((#company), params[:position_id]), { :include_blank => true, :reject_if => #company.blank? } %>
<% #industry = Position.all.map { |p| [ p.industry, p.industry ] } %>
<%= select_tag "industry", options_for_select((#industry), params[:position_id]), { :include_blank => true, :reject_if => #industry.blank? } %>
<%= submit_tag 'Filter', class: 'btn btn-large btn-primary' %>
<% end %>
and a controller (User controller):
def index
if params[:company] && params[:industry]
#users = User.companies(params[:company]).industries(params[:industry])
elsif params[:company]
#users = User.companies(params[:company])
elsif params[:industry]
#users = User.companies(params[:industry])
else
#users = User.all
end
end
A User has many companies and industries through positions:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :first_name, :last_name, :position_ids
has_many :positions
has_many :companies, :through => :positions
has_many :industries, :through => :positions
has_one :current_position, :class_name => "Position", :conditions => { :is_current => true }
scope :companies, lambda { |*company| {:include => :positions, :conditions => ["positions.company = ?", company]} }
scope :industries, lambda { |*industry| {:include => :positions, :conditions => ["positions.industry = ?", industry]} }
end
Despite the if statement in my user controller, I cannot get my view to ignore blank entries in either the company or industry field. For instance, a blank company and "Internet" industry filter returns this url:
...users?utf8=%E2%9C%93&company=&industry=Internet&commit=Filter
how do I modify my code to ignore a blank company field so that the url excludes 'company=&' entirely? In this case, I get the returned results that I want:
...users?utf8=%E2%9C%93&industry=Internet&commit=Filter
thanks!
What you need to do is check to see if the parameters are blank.
if !params[:company].blank? && !params[:industry].blank?
#users = User.companies(params[:company]).industries(params[:industry])
elsif !params[:company].blank? && params[:industry].blank?
#users = User.companies(params[:company])
elsif !params[:industry].blank? && params[:company].blank?
#users = User.companies(params[:industry])
else
#users = User.all
end
When you submit the form, the variables are being set. Just that, they have blank values. So you need to check if they are blank instead of whether they exist.

Accessing nested child attributes in parent model?

I have the following form for release, with fields for tracks being accepted as nested attributes within my release model.
<%= form_for(#release) do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id, :class => "text" %>
<%= f.text_field :title, :class => "text" %>
<%= f.fields_for :tracks do |builder| %>
<%= render 'track_fields', :f => builder %>
<% end %>
<% end %>
My release model contains:
accepts_nested_attributes_for :tracks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => :true
accepts_nested_attributes_for :releases_tracks
before_save :order_tracks
before_update :order_tracks
def order_tracks
releases_tracks.each { |t| t.position = track_attributes.position }
tracks.each { |t| t.user_id = user_id}
tracks.each { |t| t.label_id = label_id}
end
def track_attributes=(track_attributes)
track_attributes.each do |attributes|
tracks.build(attributes)
artists_tracks.build(attributes)
end
end
Everything works well, except the line below where i'm trying to take the position value entered in the fields_for part of the form. I can access values from the parent form, user_id for example, but how do I access the child values?
releases_tracks.each { |t| t.position = track_attributes.position }
Thanks all!
(Note: I don't want to use acts_as_list for this)
try to use:
releases_tracks.each { |t| t.position = track_attributes[:position] } or
releases_tracks.each { |t| t.position = track_attributes["position"] }

My form fields are being deleted on submit

And as a result its not passing validation.
This is my embedded form :
- form_for [#organization, #referral] do |f|
= f.error_messages
= render :partial => 'referral_fields', :locals => { :f => f }
= f.submit "Submit", :class => "button"
#_referral_fields.html.haml
.grid_7
.grid_1{:style => "width: 64px;"}
= f.label :org_name, "Business", :class => "right"
.grid_4
= f.text_field_tag :org_name
.grid_7
.grid_1{:style => "width: 64px;"}
= f.label :name, '', :class => "right"
.grid_4
= f.text_field_tag :name
.grid_7
.grid_1{:style => "width: 64px;"}
= f.label :email, '', :class => "right"
.grid_2.omega{:style => "width: 114px;"}
= f.text_field_tag :email, '', :style => "width: 125px;"
.grid_1.alpha
= f.label :town, '', :class => "right"
.grid_2
= f.text_field_tag :town, '', :style => "width: 100px;"
And when I click submit, SQL definately reads the data I inputted :
Processing ReferralsController#create (for ::1 at 2010-10-18 09:39:07) [POST]
Parameters: {"name"=>"asdfasd", "commit"=>"Submit", "action"=>"create", "authenticity_token"=>"/1bwOqHjojde3p0Py08mCrko8xULE4R+eXUvT6qf1cE=", "controller"=>"referrals", "org_name"=>"asdfasdf", "organization_id"=>"1", "town"=>"asdfasd", "email"=>"asdfasd"}
Not sure what I'm missing. Here is controllers and models :
#referral.rb
belongs_to :organization, :touch => true
validates_presence_of :org_name, :name, :email, :town
#referrals_controller.rb
def new
#referral = Referral.new
respond_to do |format|
format.html { render :layout => 'manage' }
end
end
def create
#referral = Referral.new(params[:referral])
if #referral.valid? && #organization.referrals << #referral
flash[:notice] = "Referrals saved."
redirect_to new_organization_referrals_path(#organization)
else
render :action => :new, :layout => 'manage'
end
end
From looking at the parameters, it doesn't look like you have your form fields setup properly?
You are using the params[:referral] hash to build the referral, but I don't see a :referral hash in your parameter list....
Your form fields should look like this:
<input name="referral[name]"/>
<input name="referral[town]"/>
<input name="referral[org_name]"/>
etc...
And then in your parameter list you should be something like { :referral => {:name => "foo", "org_name" => "bar", town => "Boise" } }

Rails collection_select

Manager :has_many :interns, :through => :assigns
Intern :has_many :managers, :through => :assigns
I am trying to create a new assign record. This is the assigns/new view where a given authenticated intern is creating a new association with a manager:
# assigns/new.html.erb
<% form_for #assign, :url => {:action => "create"} do |p| %>
<%= p.label "Select Manager", nil, :class => "label" %>
<%= collection_select :assign, :manager_id, #managers, :id, :manager_name, options ={:prompt => "Select a manager"}, html_options ={:class =>"listBox", :style => "width:25em;"} %>
<%= p.hidden_field :intern_id %>
<% end %>
# assigns controller
def new
#intern = Intern.find(params[:id])
#assign = Assign.new(:intern_id => #intern.id)
render :layout => 'centered'
end
def create
#assign = Assign.new(params[:assign])
#assign.manager_id = params[:manager_id]
if #assign.save
redirect_to :controller => "interns", :action => "home"
else
render :action => :new
end
end
The problem is: manager_id = nil. Why? Thanks very much.
Comment out following or
#assign.manager_id = params[:manager_id]
OR replace with
#assign.manager_id = params[:assign][:manager_id]
You don't need this line
#assign.manager_id = params[:manager_id]
You're already assigning the manager_id in the line before
#assign = Assign.new(params[:assign])

Resources