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])
Related
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" %>
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
Want to create a select that tells what info to pass to the partial in a Rails 3 App.
Currently.
Lets say default is
<% orders_date_range = #orders.closed_today %>
Then
<div id="reports">
<%= render :partial => "report_details", :locals => { :orders => orders_date_range } %>
</div>
Can I create a select tag to pass in the orders_date_range? Or is there a better way of doing this?
UPDATE
<% orders = #orders.closed_today %>
<% #options = [["this week", #orders.closed_this_week],["this year", #orders.closed_this_year]]%>
<%= select 'orders', 'order', #options.collect {|f| [f[0], f[1]]}, :remote => true %>
<div id="reports">
<%= render :partial => "report_details", :locals => { :orders => orders } %>
</div>
Don't know why, but would only work with 'orders', 'order' for select.
applicaton.js
$("#orders_order").change(function(){
$.getScript("reports");
});
reports.js.erb
$("#reports").html("<%= escape_javascript(render :partial => 'report_details', :locals => { :orders => params[:selected] } ) %>");
Probably would be cool to do this as an AJAX thing....
Form.erb:
#call this at the top of your view
<%= javascript_include_tag :defaults %>
<%= select 'orders', 'option', #options.collect {|f| [f[0], f[1]]}, :onchange => remote_function(:url => {:action => :render_my_partial}, :with => 'Form.Element.Serialize(this)' %>
Controller:
def form
#options = [["option1", option1],["option2", option2]...]
end
def render_my_partial
render update do |page|
page.replace_html 'reports', :partial => 'report_details', :orders => params[:orders][:option]
end
end
Excuse me, I am a newbie programmer in Rails.
I want use AJAX in a DATE SELECT. when I change the date, change the punitive ammount depends the result of method get_punitive (Model).
I use the next code in Controller, Model and View.However the event On change is not recognized. please you could help me.
Operations Model (partially)
def get_punitive(payment_date, expiration_date)
if payment_date > expiration_date
expiration_days= (payment_date - expiration_date).to_i
else
expiration_days = 0
end
punitive_ammount = (self.capital * (self.interest_rate_for_taker / 100.0) * expiration_days) / 30
# raise punitive_ammount.inspect
end
Operations Controller (partially)
def cancel
#operation = Operation.find(params[:id])
last_pagare = Pagare.find(:first, :conditions => "operation_id = #{#operation.id} AND state <> 'cancelled'")
#punitive_ammount = #operation.get_punitive(DateTime.now.to_date, last_pagare.expiration_date.to_date)
end
def update_payment_date
raise params.inspect
end
def submit_cancellation
#operation = Operation.find(params[:id])
ammount = params[:ammount]
punitive_ammount = (params[:punitive_ammount].blank?) ? 0 : params[:punitive_ammount]
payment_date = Date.new(params[:"payment_date(1i)"], params(:"payment_date(2i)"), params(:"payment_date(3i)"))
admin = User.find_by_login('admin')
if #operation.cancel(ammount, punitive_ammount, admin, payment_date)
respond_to do |format|
format.html { redirect_to(admin_operations_url) }
format.xml { head :ok }
end
else
#operation.errors.add_to_base("Los montos ingresados son invalidos")
render :action => 'cancel'
end
View of cancel
Cancelacion de Operaciones
<% form_for(#operation, :url => submit_cancellation_admin_operation_path) do |f| %>
<%= f.error_messages %>
<%= text_field_tag :a, :onClick => "javascript:alert('hola');" %>
<p>Fecha de Pago:<br/><br/>
<%= date_select("", :payment_date, {:start_date => Time.now, :onchange => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'payment_date='+value")}) %>
</p>
<p>Prueba
<%= collection_select "", :object, Operation.all, :id, :taker_id, { :onChange => "javascript::alert('hola');", :onClick => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'dgdfg='+value")} %>
</p>
<p>Monto a Cancelar (Mayor a cero):<br/><br/>
<%= text_field_tag :ammount , #operation.get_balance(#operation.interest_rate_for_taker) %>
</p>
<p>Monto punitorio:<br/><br/>
<%= text_field_tag :punitive_ammount, #punitive_ammount %>
</p>
<!--<p>Fecha de Pago:<br/><br/>
<%#= date_select("", :date, :start_year => Time.now.year-1, :default => Time.now) %>
</p>-->
<% %>
<p>
<%= f.submit 'Cancelar' %>
</p>
<% end %>
Hi format of date_select helper is
date_select(object_name, method, options = {}, html_options = {})
you have
<%= date_select("", :payment_date, {:start_date => Time.now, :onchange => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'payment_date='+value")}) %>
try
<%= date_select("", :payment_date, {:start_date => Time.now}, {:onchange =>"javascript::alert('hola');"}) %>
the same about collection_select
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
you have
<%= collection_select "", :object, Operation.all, :id, :taker_id, { :onChange => "javascript::alert('hola');", :onClick => remote_function(:url => {:controller => 'operations', :action => "update_payment_date"}, :with => "'dgdfg='+value")} %>
try
<%= collection_select "", :object, Operation.all, :id, :taker_id, {}, { :onChange => "javascript::alert('hola');"}%>
My current working environment is Rails 2.3.8 (various reasons why my company hasn't moved to Rails 3).
I'm trying to update elements of a multi-model form via AJAX calls - the idea being to replace certain dropdowns depending on how the user selects or fills in other fields.
I have previously managed to get this working by using non-form based partials - the problem I have now is to reproduce the AJAX updating of the select dropdowns when the partials are based around form_for and fields_for.
Sorry for the following wall of text - i've tried to cut it down as much as possible (the code itself does work on my test site).
How do I generate the form builder elements in the Outbreak controller and then pass this to the category partial to take the place of incident_form?
Any pointers would be great :D
Models
class Outbreak < ActiveRecord::Base
has_many :incidents, :dependent => :destroy
has_many :locations, :through => :incidents
accepts_nested_attributes_for :locations, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :incidents, :allow_destroy => true, :reject_if => :all_blank
end
class Incident < ActiveRecord::Base
belongs_to :outbreak
belongs_to :location
belongs_to :category
belongs_to :subcategory
belongs_to :subtype
end
class Location < ActiveRecord::Base
has_many :incidents, :dependent => :destroy
has_many :outbreaks, :thorugh => incidents
end
Views
_form
<% form_for(#outbreak, :html => {:multipart => true}) do |form| %>
<%= render :partial => 'outbreak_type_select', :locals => {:outbreak_types => #outbreak_types, :f => form } %>
<% form.fields_for :incidents do |incident_form| %>
<%= render :partial => 'category_select', :locals => {:categories => #categories, :incident_form => incident_form} %>
<%= render :partial => 'subcategory_select', :locals => { :subcategories => #subcategories, :incident_form => incident_form } %>
<% end %>
<% end %>
_outbreak_type_select
<% with_str = "'outbreak_type=' + value " %>
<% if #outbreak.id %>
<% with_str << "+ '&id=' + #{outbreak.id}" %>
<% end %>
<%= f.collection_select(:outbreak_type, #outbreak_types, :property_value, :property_value, {}, {:onchange => "#{remote_function(:url => { :action => "update_select_menus"}, :with => with_str)}"} ) %>
_category_select
After calling update_select_menus how to generate the incident_form
<%= incident_form.collection_select( :category_id, #categories, :id, :name, {:prompt => "Select a category"}, {:onchange => "#{remote_function(:url => { :action => "update_subcategory"}, :with => "'category_id='+value")}"}) %>
RJS
begin
page.replace_html 'outbreak_transmission_div', :partial => 'outbreaks/transmission_mode_select', :locals => {:transmission_modes => #transmission_modes }
rescue
page.insert_html :bottom, 'ajax_error', '<p>Error :: transmission modes update select</p>'
page.show 'ajax_error'
end
begin
page.replace_html 'incident_category_select', :partial => 'outbreaks/category_select', :locals => { :categories => #categories }
rescue
page.insert_html :bottom, 'ajax_error', '<p>Error :: incident category update select</p>'
page.show 'ajax_error'
end
Controllers
Outbreak
def new
#outbreak = Outbreak.new
#outbreak.incidents.build
#outbreak.locations.build
#just the contents for the dropdowns
#categories = Category.find(:all, :conditions => {:outbreak_type => "FOODBORNE"}, :order => "outbreak_type ASC")
#subcategories = Subcategory.find(:all, :order => "category_id ASC")
end
def update_select_menus
#outbreak_type = params[:outbreak_type].strip
if params[:id]
#outbreak = Outbreak.find(params[:id])
else
#outbreak = Outbreak.new
#outbreak.incidents.build
#outbreak.locations.build
end
if #outbreak_type == "FOODBORNE"
ob_type_query = "OUTBREAKS:TRANSMISSION_MODE:" << #outbreak_type
#transmission_modes = Property.find(:all, :conditions => {:field => ob_type_query})
ob_type_query = "INVESTIGATIONS:CATEGORY:" << #outbreak_type
#sample_types = Property.find(:all, :conditions => {:field => ob_type_query})
#categories = Category.find(:all, :conditions => { :outbreak_type => "FOODBORNE"})
#subcategories = Subcategory.find(:all, :conditions => { :category_id => #categories.first.id})
#subtypes = Subtype.find(:all, :conditions => { :subcategory_id => #subcategories.first.id})
elsif #outbreak_type == "NON-FOODBORNE"
ob_type_query = "OUTBREAKS:TRANSMISSION_MODE:" << #outbreak_type
#transmission_modes = Property.find(:all, :conditions => {:field => ob_type_query})
ob_type_query = "INVESTIGATIONS:CATEGORY:" << #outbreak_type
#sample_types = Property.find(:all, :conditions => {:field => ob_type_query})
#categories = Category.find(:all, :conditions => { :outbreak_type => "NON-FOODBORNE"})
#subcategories = Subcategory.find(:all, :conditions => { :category_id => #categories.first.id})
#subtypes = Subtype.find(:all, :conditions => { :subcategory_id => #subcategories.first.id})
end
respond_to do |format|
format.html
format.js
end
end
Found a work around based on http://www.treibstofff.de/2009/07/12/ruby-on-rails-23-nested-attributes-with-ajax-support/
This should probably go in Outbreak helper (in Outbreak controller atm)
def update_select_menus
#outbreak_type = params[:outbreak_type].strip
#next_child_index will only be used if
#next_child_index ? params[:next_child_index] : 0
if params[:id]
#outbreak = Outbreak.find(params[:id])
else
#outbreak = Outbreak.new
#outbreak.risks.build
#outbreak.incidents.build
#outbreak.locations.build
end
if #outbreak_type == "FOODBORNE"
ob_type_query = "OUTBREAKS:TRANSMISSION_MODE:" << #outbreak_type
#transmission_modes = Property.find(:all, :conditions => {:field => ob_type_query})
ob_type_query = "INVESTIGATIONS:CATEGORY:" << #outbreak_type
#sample_types = Property.find(:all, :conditions => {:field => ob_type_query})
#categories = Category.find(:all, :conditions => { :outbreak_type => "FOODBORNE"})
#subcategories = Subcategory.find(:all, :conditions => { :category_id => #categories.first.id})
#subtypes = Subtype.find(:all, :conditions => { :subcategory_id => #subcategories.first.id})
elsif #outbreak_type == "NON-FOODBORNE"
ob_type_query = "OUTBREAKS:TRANSMISSION_MODE:" << #outbreak_type
#transmission_modes = Property.find(:all, :conditions => {:field => ob_type_query})
ob_type_query = "INVESTIGATIONS:CATEGORY:" << #outbreak_type
#sample_types = Property.find(:all, :conditions => {:field => ob_type_query})
#categories = Category.find(:all, :conditions => { :outbreak_type => "NON-FOODBORNE"})
#subcategories = Subcategory.find(:all, :conditions => { :category_id => #categories.first.id})
#subtypes = Subtype.find(:all, :conditions => { :subcategory_id => #subcategories.first.id})
end
#pathogen_types = Property.find(:all, :conditions => {:field => "PATHOGENS:CATEGORY"})
#outbreak_types = Property.find(:all, :conditions => {:field => "OUTBREAKS:OUTBREAK_TYPE"} )
render :update do |page|
page.replace 'outbreak_transmission_div', :partial => 'transmission_mode_select_update'
page.replace 'incident_category_select', :partial => 'incident_category_select_update'
page.replace 'incident_subcategory_select', :partial => 'incident_subcategory_select_update'
page.replace 'incident_subtype_select', :partial => 'incident_subtype_select_update'
end
end
In the Outbreak view (although since this partial is related to Incident it should probably go in that view instead)
<% ActionView::Helpers::FormBuilder.new(:outbreak, #outbreak, #template, {}, proc{}).fields_for :incidents,{:child_index => #next_child_index} do |this_form| %>
<div id="incident_category_select">
<%= render :partial => 'category_select', :locals => {:incident_form => this_form } %>
</div>
<% end %>
The ActionView::Helpers::FormBuilder is used to produce the required fields_for form - The website article goes through this in more detail.
The resulting index is set by the #next_child_index variable which can be passed to the controller by the original AJAX call (for example #next_child_index = 1, then the resulting form element name will be outbreak [incidents_attributes] [1] [category_id] ) - I haven't used this in this example because although in future I want the form to support more than one location per Outbreak for this initial run-through it will just accept a single Location - Incident per Outbreak.
_category_select.erb partial (in Outbreak view atm)
<% with_str = "'category_id=' + value " %>
<% if #outbreak.id %>
<% with_str << "+ '&id=' + #{#outbreak.id}" %>
<% end %>
<%= incident_form.collection_select( :category_id, #categories, :id, :name, {:prompt => "Select a category"}, {:onchange => "#{remote_function(:url => { :action => "update_subcategory"}, :with => with_str)}"}) %>
The with_str is just to optionally pass the Outbreak id if it exists to the controller to find the Outbreak record to produce the form and if not to build a new Outbreak and associated nested attributes like Incidents and Locations.
The must be neater ways of doing this - especially the FormHelper and passing the Outbreak id via the optional with string.