Rails5 what on earth is this assignment.errors showing me - ruby-on-rails

I have a form I'm using for submission..I've got a gnarly method "create_shift" in my controller to handle said form...but here is the catcher... have to use a preexisting database and the relations are....interesting
the form fails to submit with a "method_missing" error. Doing a assignment.errors gives me this output that I do. not. understand.
What on earth is this telling me? I have missing form fields? When I try to submit the form with "attendance_type" and "call_status_type" coded in via my "create_shift" I still get a different error which I'll list at the bottom of this post...
So first the error output I get with NO.."attendance_type" and "call_status_type" added in my "create_shift"...
_form.html.erb
<!--This is NEW action form-->
<%= form_for #assignment, :url => #my_url, remote: true do |f| %>
<!-- #FIXME need a fields_for 4 the volunteer_event-->
<div class="">
<div class="modal-body d-flex">
<div class="col-sm-8 border-right">
<section id="location-date-time-notes" class="flex">
<% if #assignment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#assignment.errors.count, "error") %> prohibited this assignment from being saved:</h2>
<ul>
<% #assignment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<!--VOLUNTEER SHIFT-->
<!--TODO: make this a partial under field_for-->
<%= f.fields_for :volunteer_event do |builder| %>
<%= render 'assignments/volunteer_shift_fields', vs: builder %>
<% end %>
<!--TODO: Volunteer Shift end -->
<div id="time-row" class="d-flex flex-row">
<label for="assignment_time" class="col-sm-3 p-2">
<i class="fa fa-clock-o fa-lg" aria-hidden="true"></i> Time:
</label>
<div class="col- p-2">
<div class="myStartTime" id="start_time_<%= #assignment.id %>">
<%= f.time_select :start_time %>
</div>
</div>
<div class="col- p-2"><i class="fa fa-arrows-h fa-lg" aria-hidden="true"></i></div>
<div class="col-sm-3 p-2">
<div class="myEndTime" id="end_time_<%= #assignment.id %>">
<%= f.time_select :end_time %>
</div>
</div>
</div>
<div class="d-flex flex-row">
<label for="assignment_notes" class="col-sm-3 p-2">
<i class="fa fa-clipboard fa-lg" aria-hidden="true"></i> Notes:
</label>
<div class="col-sm-9 p-2">
<div class="d-flex flex-row">
<span> Notes only get saved if a contact is assigned the shift, and get removed when the contact is removed from the shift.</span>
<div class="">
<%= f.label :notes %>
<%= f.text_area :notes %>
</div>
</div>
</div>
</div>
</section>
</div>
<div class="col-sm-4">
<!-- Contact Section-->
<div id="contact_section">
<% if #assigned_contacts && #assigned_contacts.length > 0 %>
<h2>Previously Assigned Contacts</h2>
<% #assigned_contacts.each do |c| %>
<%= label_tag "assigned_contacts[#{c.id}]", "Are you sure you want to remove the currently scheduled volunteer, #{c.display_name} (##{c.id}), from the assignment(s)?" %>
<%= check_box_tag "assigned_contacts[#{c.id}]", "replace", #replaced_contacts.include?(c.id) %>
<% end %>
<% end %>
<input id="contact_element_prefix" name="contact_element_prefix" type="hidden" value="contact">
<div class="name large flex-row">
<%= f.label :contact_id %><%= f.text_field :contact_id %>
</div>
<div id="display-contact" class="d-flex flex-row">
<% if f.object.contact_id %>
<%= render partial: 'contacts/contact_display', locals: { contact:f.object.contact} %>
<% else %>
<div>no contact attatched- _form.html called</div>
<%#= link_to 'Show Contact', contact_path(f.object.contact_id), remote: true %>
<% end %>
</div>
<!-- FIXME: replace this logic stack with AJAX-->
<%#= contact_field("#obj", "contact_id",
:locals => {:options => {
:object_name => f.object_name.to_s,
:field_name => 'contact_id',
:on_display => 'display_disciplinary_notes(); display_contact_notes();'
}}
) %>
<%= f.label :closed, "Is this slot closed?" %>
<%= f.check_box :closed %>
<!--Contact Section END-->
<!--Attendance / Call Status start-->
<% if f.object.id && f.object.contact_id %>
<div class="flex-row">
<div class="col-25"><label for="assignment_attendance_type_id">Attendance:</label></div>
<div class="col-75"><%= select(f.object_name,
"attendance_type_id",
AttendanceType.all.sort_by(&:id).collect {|p| [ p.name, p.id ] },
:include_blank => true) %></div>
</div>
<div class="flex-row">
<div class="col-25"><label for="assignment_call_status_type_id">Call status:</label></div>
<div class="col-75"><%= select(f.object_name,
"call_status_type_id",
([["not called yet", ""]] + CallStatusType.all.sort_by(&:id).collect {|p| [ p.name, p.id ] }),
:include_blank => false) %></div>
</div>
<% end %>
<!-- Attendance / Call Status End-->
<!-- LOCK VERSION-->
<div class="flex-row">
<div class="col-25">
<%= f.label :lock_version %>
</div>
<div class="col-75">
<%= f.number_field :lock_version %>
</div>
</div>
<!-- LOCK end-->
</div>
</div>
</div>
<div class="modal-footer d-flex justify-content-between">
<div class="edit_icons d-flex flex-row">
<div class="d-flex flex-column">
<!-- <i class="fa fa-share-alt-square fa-lg" aria-hidden="true"></i> Split-->
<!-- <i class="fa fa-files-o fa-lg" aria-hidden="true"></i> Copy-->
</div>
<div class="d-flex flex-column">
<%#= link_to '<i class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></i>Edit'.html_safe, edit_assignment_path, remote: true%>
<!-- <i class="fa fa-refresh fa-lg" aria-hidden="true"></i> Reassign-->
</div>
</div>
<div>
<button type="button" class="btn btn-secondary mr-2" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary"><%= f.submit "Submit" %></button>
<!-- <input id="assignment_submit" name="commit" type="submit" value="Update">-->
</div>
</div>
</div>
<% end %>
Here is the Model
assignment.rb
class Assignment < ApplicationRecord
# attr_accessor :volunteer_event ,:contact_id #why is this volunteer_event and not volunteer_shift???
belongs_to :volunteer_shift
has_one :volunteer_task_type, :through => :volunteer_shift, :source => :volunteer_task_type
belongs_to :contact ,optional: true
validates_presence_of :volunteer_shift #belongs_to takes care of this now
validates_associated :volunteer_shift
belongs_to :attendance_type
belongs_to :call_status_type
validates_presence_of :set_date, :if => :volshift_stuck #belongs_to takes care of this now??
accepts_nested_attributes_for :volunteer_shift, allow_destroy: true
delegate :set_date, :set_date=, :to => :volunteer_shift
delegate :set_description, :set_description=, :to => :volunteer_shift
has_one :contact_volunteer_task_type_count, lambda{||
{:conditions => 'contact_volunteer_task_type_counts.contact_id = #{defined?(attributes) ? contact_id : "assignments.contact_id"}', :through => :volunteer_shift, :source => :contact_volunteer_task_type_counts}
}
scope :date_range, lambda { |range|
joins(volunteer_shift: :volunteer_event)
.where(volunteer_shifts: { volunteer_events: { date: range } })
}
scope :is_after_today, lambda {||
{ :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) > ?', Date.today] }
}
scope :on_or_after_today, lambda {||
{ :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) >= ?', Date.today] }
}
scope :not_cancelled, -> { where('(attendance_type_id IS NULL OR attendance_type_id NOT IN (SELECT id FROM attendance_types WHERE cancelled = \'t\'))')}
scope :roster_is_limited_by_program, -> {where("roster_id IN (SELECT id FROM rosters WHERE limit_shift_signup_by_program = 't')").joins(:volunteer_shift)}
def real_programs
return [] unless self.volunteer_shift&.roster
return [] unless self.volunteer_shift.roster.limit_shift_signup_by_program
self.volunteer_shift.roster.skeds.select{|x| x.category_type == "Program"}.map{|x| x.name}
end
attr_accessor :attendance_type_id
# TODO: find all time_range_s methods and either pull out to DRY or give unique names
def time_range_s
return "" unless start_time and end_time
(start_time.strftime("%I:%M") + ' - ' + end_time.strftime("%I:%M")).gsub( ':00', '' ).gsub( ' 0', ' ').gsub( ' - ', '-' ).gsub(/^0/, "")
end
def description
return unless volunteer_shift
self.volunteer_shift.volunteer_event.date.strftime("%D") + " " + self.time_range_s + " " + self.slot_type_desc
end
def roster_title
return unless volunteer_shift
self.volunteer_shift.roster.name
end
def date
return unless volunteer_shift
volunteer_shift.date
end
#full calendar uses this method name....see the assignment.json.jbuilder
def event_date
return unless volunteer_shift
self.date
end
def slot_type_desc
b = (self.volunteer_shift.volunteer_task_type_id.nil? ? self.volunteer_shift.volunteer_event.description : self.volunteer_shift.volunteer_task_type.description)
b = b + " (#{self.volunteer_shift.description})" if self.volunteer_shift.description and self.volunteer_shift.description.length > 0
b
end
def display_name
((!(self.volunteer_shift.description.nil? or self.volunteer_shift.description.blank?)) ? self.volunteer_shift.description + ": " : "") + self.contact_display
end
def cancelled?
(self.attendance_type&.cancelled)
end
def attended?
(self.attendance_type and !self.attendance_type.cancelled)
end
def contact_display
if self.closed
"(closed)"
elsif contact_id.nil?
return "(available)"
else
self.contact.display_name + "(#{self.voltask_count})"
end
end
before_validation :set_values_if_stuck
def set_values_if_stuck
return unless (volshift_stuck || volunteer_shift)
volunteer_shift.set_values_if_stuck(self)
end
after_destroy { |record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.destroy; else VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available; end}
after_save {|record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.save; end}
after_save { |record| VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available }
def volunteer_shift_attributes=(attrs)
return unless volunteer_shift
self.volunteer_shift.attributes=(attrs) # just pass it up
end
def volshift_stuck
return unless volunteer_shift
self.volunteer_shift&.stuck_to_assignment
end
#for fullcalendar
def all_day_event?
self.start_time == self.start_time.midnight && self.end_time == self.end_time.midnight ? true : false
end
end
and controller
class AssignmentsController < ApplicationController
before_action :set_assignment, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token #TODO refactor this line to be very specific
# GET /assignments or /assignments.json
def index
# #assignments = Assignment.limit(20)
# #assignments = Assignment.where(start: params[:start]..params[:end])
#assignments = Assignment.date_range(params[:start]..params[:end])
end
# GET /assignments/1 or /assignments/1.json
def show
end
# GET /assignments/new
def new
# #assignment = Assignment.new
add_shift
# #assignment.volunteer_shift.build
#my_url = {:action => "create", :id => params[:id]}
end
# GET /assignments/1/edit
def edit
end
def edit_old #dumb "stuff" from older app
if #assignment
#assignments = [#assignment]
else
begin
#assignments = params[:id].split(",").map{|x| Assignment.find(x)}
#assignment = #assignments.first
rescue
flash[:error] = $!.to_s
redirect_skedj(request.env["HTTP_REFERER"], "")
return
end
end
#referer = request.env["HTTP_REFERER"]
#my_url ||= {:action => "update", :id => params[:id]}
render :action => 'edit'
end
# POST /assignments or /assignments.json
def create
create_shift
# #assignment = Assignment.new(assignment_params)
#
# # error wants contact.id not contact_id ???
#
# respond_to do |format|
# if #assignment.save
# format.html { redirect_to #assignment, notice: "Assignment was successfully created." }
# format.json { render :show, status: :created, location: #assignment }
# else
# format.html { render :new, status: :unprocessable_entity }
# format.json { render json: #assignment.errors, status: :unprocessable_entity }
# end
# end
end
def add_shift # FIXME: evil brought over from old app
ve = nil
if !params["id"].blank?
ve = VolunteerEvent.find_by_id(params["id"])
else
ve = VolunteerEvent.new
end
vs = ve.volunteer_shifts.new
vs.program = Program.find_by_name("intern")
# vs.slot_count = 1
vs.volunteer_event_id = ve.id if ve.id
vs.volunteer_event = ve
a = vs.assignments.new
a.volunteer_shift = vs
vs.stuck_to_assignment = true
vs.not_numbered = true
#assignments = vs.assignments = [a]
#referer = request.env["HTTP_REFERER"]
#my_url = {:action => "create_shift", :id => params[:id]}
#assignment = a
# binding.pry
# render :partial => 'assignments/new'
# render :partial => 'assignments/edit' #<--original
end
def create_shift # FIXME: evil brought over from original code base
# #fonso = #assignment.inspect
ve = nil
# Fixme: building volunteer shifts variable "vs" and associating with assignment
if !params["id"].blank?
ve = VolunteerEvent.find(params["id"])
else
if params["roster_id"].blank? || params["assignment"]["set_date"].blank?
ve = VolunteerEvent.new # won't save
else
ve = Roster.find_by_id(params["roster_id"]).vol_event_for_date(params["assignment"]["set_date"])
end
end
vol_shift = ve.volunteer_shifts.new
vol_shift.stuck_to_assignment = true
vol_shift.not_numbered = true
#fixme: volunteer shifts variable "vol_shift" and association with assignment end
call_status_type = CallStatusType.find_by_id(params["assignment"]["call_status_type_id"]) #fixme: this does not fix the problem
attendance_type = AttendanceType.find_by_id(params["assignment"]["attendance_type_id"]) #fixme: this does not fix the problem
# FIXME: vs.attributes=(params["assignment"]["volunteer_shift_attributes"]) # original needs to be rebuilt 4 this system
h0 = {"volunteer_task_type_id" => params["volunteer_task_type_id"]}
h1 = {"roster_id" => params["roster_id"]}
h2 = {"program_id" => params["program_id"]}
h3 = {"set_description" => params["set_description"]}
#h4 = {"attendance_type" => attendance_type.name} #fixme: this does not fix the problem
#h5 = {"call_status_type" => call_status_type} #fixme: this does not fix the problem
hash_arr = [h0,h1,h2,h3] #fixme: no h4 or h5
volunteer_shift_attributes = hash_arr.reduce { |acc, h| (acc || {}).merge h }
#binding.pry
vol_shift.attributes = volunteer_shift_attributes #fixme: fracks up here but why?
#fixme: vs.attributes fix end
#FIXME: building variable - #assignments END
assignment = vol_shift.assignments.new
vol_shift = assignment.volunteer_shift
assignment.attributes = (assignment_params) #<----magic happens here
#assignments = [assignment]
#fixme: building variable - #assignments END
#FIXME: wtf is it and why is it?
vol_shift.assignments = [assignment]
vol_shift.set_values_if_stuck #fixme: <---- drill into this one
binding.pry
vs.assignments = []
#success = assignment.valid? && vs.save #fixme: <--------what was the valid? error here?
#assignment = assignment #fixme: <-----------------------#assignment is finally built here
# fixme: the above lines are merging params from one into the other in the old app. to create the new volunteer_shift.
respond_to do |format|
if #success
vol_shift = vol_shift.reload
#assignment = a = vol_shift.assignments.new
a.volunteer_shift = vol_shift
# a.volunteer_shift_id = vs.id
a.attributes = (params["assignment"])
#assignments = vol_shift.assignments = [a]
format.html { redirect_to #assignment, notice: "Assignment was successfully created." }
format.json { render :show, status: :created, location: #assignment }
else
vs.destroy
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #assignment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /assignments/1 or /assignments/1.json
# def update -original
#
# #assignment.update(assignment_params)
# end
def update
unless params[:assignment]
redirect_to :action => "index"
return
end
#my_url = {:action => "update", :id => params[:id]}
last_id = nil
begin
#assignments = params[:id].split(",").map{|x| last_id = x; Assignment.find(x)}
rescue ActiveRecord::RecordNotFound
flash[:jsalert] = "The assignment (##{last_id.to_i.inspect}) seems to have disappeared or never existed. It is possible somebody else has modified or deleted it."
rt = params[:assignment].delete(:redirect_to)
redirect_skedj(rt, "")
return
end
lv = params["lock_versions"]
ac = params["assigned_contacts"] || {}
#assigned_contacts = []
#replaced_contacts = []
ret = true
#assignments.each do |as|
as.lock_version = lv[as.id.to_s]
if as.lock_version_changed?
as.errors.add("lock_version", "is stale for this assignment, which means it has been edited by somebody else since you opened it, please try again")
ret = false
end
if as.contact_id && as.contact_id.to_s != params[:assignment][:contact_id].to_s
#assigned_contacts << as.contact
unless ac[as.contact_id.to_s] && ac[as.contact_id.to_s] == "replace"
as.errors.add("contact_id", "has been changed, please confirm below that the volunteer who is already assigned to the shift should be removed")
ret = false
else
#replaced_contacts << as.contact_id
end
end
end
rt = params[:assignment].delete(:redirect_to)
js_alert = nil
if ! ret
#assignment = Assignment.new
#assignment.volunteer_shift = #assignments.first.volunteer_shift
#assignment.attributes=(params[:assignment]) # .. ? .delete("volunteer_shift_attributes")
end
#assignments.each{|x|
if ret
#assignment = x
bc = x.contact_id
ret = !!(x.update_attributes(params[:assignment]))
if bc != x.contact_id and x.first_time_in_area?
alert = "#{x.contact.display_name} (##{x.contact_id}) has never logged hours for the #{x.volunteer_shift.volunteer_task_type.description} task type. Please remind the volunteer of the requirements for this area."
if x.volunteer_shift.volunteer_event and x.volunteer_shift.volunteer_event.notes and x.volunteer_shift.volunteer_event.notes.length > 0
alert += "\n\nSome suggested notes saved in the database for this event are:\n" + x.volunteer_shift.volunteer_event.notes
end
js_alert = alert
end
end
}
if ret && #assignment.contact and not #assignment.contact.is_old_enough?
msg = "This volunteer is not yet #{Default['minimum_volunteer_age']} years old (based on their saved birthday: #{#assignment.contact.birthday.to_s}).\nPlease remind the volunteer that they must have an adult with them to volunteer."
if js_alert == nil
js_alert = msg
else
js_alert = msg + "\n\n" + js_alert
end
end
flash[:jsalert] = js_alert if js_alert
if ret
flash[:notice] = 'Assignment was successfully updated.'
redirect_skedj(rt, #assignment.volunteer_shift.date_anchor)
else
#referer = rt
render :action => "edit"
end
end
# DELETE /assignments/1 or /assignments/1.json
def destroy
#assignment.destroy
# NOTE: comment original out 4 now
# respond_to do |format|
# format.html { redirect_to assignments_url, notice: "Assignment was successfully destroyed." }
# format.json { head :no_content }
# end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_assignment
#assignment = Assignment.find(params[:id])
end
# Only allow a list of trusted parameters through.
def assignment_params
#fixme: ,volunteer_shift_attributes: [:???, :???, :???] <--- insert this below?
params.require(:assignment).permit(:title, :set_date, :date, :date_range, :volunteer_shift_id, :contact_id, :start_time, :end_time, :start, :end, :attendance_type_id, :notes, :call_status_type_id, :closed, :lock_version, :color, :description, volunteer_shift_attributes: [:volunteer_task_type_id,:roster_id,:program_id,:set_description,:set_date,:id,:destroy])
# params.require(:assignment).permit(:title, :set_date, :date_range, :contact_id, :start_time, :end_time, :start, :end, :attendance_type_id, :notes, :call_status_type_id, :closed, :lock_version, :color, volunteer_shift_attributes: [:volunteer_task_type_id,:roster_id,:program_id,:set_description,:set_date,:id,:destroy])
end
end
oh and the volunteer_shift.rb model
class VolunteerShift < ApplicationRecord
validates_presence_of :roster_id
validates_presence_of :end_time
validates_presence_of :start_time
has_many :assignments
belongs_to :volunteer_default_shift
belongs_to :volunteer_task_type
belongs_to :roster
belongs_to :volunteer_event
belongs_to :program
has_many :contact_volunteer_task_type_counts, :primary_key => 'volunteer_task_type_id', :foreign_key => 'volunteer_task_type_id' #:through => :volunteer_task_type
def validate
errors.add("end_time", "is before the start time") unless self.start_time && self.end_time && self.start_time < self.end_time
end
def self.week_for_date(d)
long_time_ago = Date.new(1901, 12, 22)
difference = (d - long_time_ago).to_int
((difference / 7) % 2 ) == 0 ? "A" : "B"
end
def weeknum
1 + ((self.date.day - 1) / 7)
end
def week
VolunteerShift.week_for_date(self.date)
end
def slot_number=(a)
write_attribute(:slot_number, a)
self.not_numbered = (!slot_number)
end
def set_description
self.description
end
def set_description=(desc)
self.description=(desc)
end
def set_date_set
binding.pry
#set_date_set #fixme: <----- nil here...breaking here?
end
def set_date=(val)
binding.pry
#set_date_set = true
#set_date = val
end
def set_date
#set_date_set ? #set_date : self.volunteer_event.date
end
def set_values_if_stuck(assn_in = nil)
return unless self.stuck_to_assignment #<---it's a boolean in the database
assn = assn_in || self.assignments.first
return unless assn
self.start_time = assn.start_time
self.end_time = assn.end_time
return unless self.volunteer_event_id.nil? || self.volunteer_event.description.match?(/^Roster #/)
# return unless set_date_set #fixme:<--- pry me...is this asking if date is set??
roster = Roster.find_by_id(self.roster_id)
if roster and !(set_date == nil || set_date == "")
ve = roster.vol_event_for_date(set_date)
ve.save! if ve.id.nil?
self.volunteer_event = ve
self.volunteer_event_id = ve.id
else
if self.volunteer_event.nil?
self.volunteer_event = VolunteerEvent.new
end
end
end
def shift_display
time_range_s + ((!(self.description.nil? or self.description.blank?)) ? (": " + self.description) : "")
end
def time_range_s
return unless self.read_attribute(:start_time) and self.read_attribute(:end_time)
(self.my_start_time("%I:%M") + ' - ' + self.my_end_time("%I:%M")).gsub( ':00', '' ).gsub( ' 0', ' ').gsub( ' - ', '-' ).gsub(/^0/, "")
end
def my_start_time(format = "%H:%M")
read_attribute(:start_time).strftime(format)
end
def self._parse_time(time)
Time.mktime(2000, 01, 01, *time.split(":").map(&:to_i))
end
def my_start_time=(str)
write_attribute(:start_time, VolunteerShift._parse_time(str))
end
def my_end_time(format = "%H:%M")
read_attribute(:end_time).strftime(format)
end
def my_end_time=(str)
write_attribute(:end_time, VolunteerShift._parse_time(str))
end
def self.range_math(*ranges)
... #cutting this out so the question can fit this post
end
def fill_in_available
return if self.stuck_to_assignment #<-- it's a boolean in the database
Thread.current['volskedj_fillin_processing'] ||= []
if Thread.current['volskedj_fillin_processing'].include?(self.id)
return
end
begin
Thread.current['volskedj_fillin_processing'].push(self.id)
Assignment.where(volunteer_shift_id: self.id).select{|x| x.contact_id.nil? and !x.closed}.each{|x| x.destroy}
inputs = [[(self.read_attribute(:start_time)), (self.read_attribute(:end_time))]]
Assignment.where(volunteer_shift_id: self.id).select{|x| !x.cancelled?}.each{|x|
inputs.push([(x.start_time), (x.end_time)])
}
results = self.class.range_math(*inputs)
results.each{|x|
a = Assignment.new
a.volunteer_shift_id, a.start_time, a.end_time = self.id, x[0], x[1]
a.volunteer_shift = self
a.closed = self.volunteer_event.nowalkins
a.save!
}
ensure
Thread.current['volskedj_fillin_processing'].delete(self.id)
end
end
after_save :fill_in_available
def date
self.volunteer_event.date
end
def date_display
self.date.strftime('%A, %B %d, %Y').gsub( ' 0', ' ' )
end
def date_anchor
self.date ? self.date.strftime('%Y%m%d') : ''
end
def time_shift(val)
self.start_time += val
self.end_time += val
end
def left_method_name
[self.volunteer_task_type_id.nil? ? self.volunteer_event.description : self.volunteer_task_type.description, self.slot_number].select{|x| !x.nil?}.join(", ")
end
def left_unique_value
left_method_name
end
def description_and_slot
((self.volunteer_task_type_id || -1) * 1000) + (self.not_numbered ? 0 : self.slot_number)
end
def weekday
Weekday.find_by_id(self.date.strftime("%w"))
end
end
And now here is the error output I get WITH.."attendance_type" and "call_status_type" added in my "create_shift"...
(FYI: they are added by h4 and h5 to the hash in the create_shift method)...I get this error...
ActiveModel::UnknownAttributeError - unknown attribute 'attendance_type' for VolunteerShift.:

h4 = {"attendance_type" => attendance_type.name} #fixme: this does not fix the problem is the cause of your problem here.
h4 get's wrapped up into an array and then the whole array get's shoved into volunteer_shift_attributes
volunteer_shift_attributes = hash_arr.reduce { |acc, h| (acc || {}).merge h }
Which in turn get's assigned to the volunteer_shift record that does not have an attendence_type column in your database. To get past this error just comment out the line
#h4 = {"attendance_type" => attendance_type.name} #fixme: this does not fix the problem is the cause of your problem here.
This leaves you with a logic error, you presumably need to set the attendance_type value on something, probably your assignment record but get that commented out and see where that leaves you, you can worry about the assignment after you have got past this error. That's a logic problem to solve not a coding error

Related

Rails5: getting a form submission error and confused as to why [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Ok, so I'm trying to update an old app by rebuilding it in a seperate Rails 5 app that points to the same database (well not really the --same-- but a clone of that DB)
I've recently tried using a nested form field approach to solve my "create new record" problem for this particular form but got jammed up for some reason....
soooooo...
I've gone back and tried a different approach by building a new event in the controller new action called "add_shift" and assigning each field individually. Then in my "create" using a method called create_shift.
NOTE: this was the technique used in the old app as well so I'm trying to port it over to the newer app...here is the error I am getting
the error
Started POST "/assignments" for blah-my-ip at 2021-11-08 06:48:49 -0800
Cannot render console from blah-my-ip! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
ActiveRecord::SchemaMigration Load (0.5ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by AssignmentsController#create as JS
Parameters: {"utf8"=>"✓", "volunteer_task_type_id"=>"41", "roster_id"=>"7", "program_id"=>"9", "set_description"=>["fonso nov8 test"], "set_date"=>["2021-01-05"], "assignment"=>{"start_time(1i)"=>"2021", "start_time(2i)"=>"11", "start_time(3i)"=>"8", "start_time(4i)"=>"08", "start_time(5i)"=>"00", "end_time(1i)"=>"2021", "end_time(2i)"=>"11", "end_time(3i)"=>"8", "end_time(4i)"=>"09", "end_time(5i)"=>"00", "notes"=>"Nov888", "contact_id"=>"166574", "closed"=>"0", "lock_version"=>"0"}, "contact_element_prefix"=>"contact", "commit"=>"Submit"}
VolunteerTaskType Load (0.2ms) SELECT "volunteer_task_types".* FROM "volunteer_task_types" WHERE "volunteer_task_types"."id" = $1 LIMIT $2 [["id", 41], ["LIMIT", 1]]
Roster Load (0.1ms) SELECT "rosters".* FROM "rosters" WHERE "rosters"."id" = $1 LIMIT $2 [["id", 7], ["LIMIT", 1]]
Program Load (0.1ms) SELECT "programs".* FROM "programs" WHERE "programs"."id" = $1 LIMIT $2 [["id", 9], ["LIMIT", 1]]
(0.1ms) BEGIN
(0.1ms) ROLLBACK
Rendering assignments/new.html.erb within layouts/application
Rendered assignments/new.html.erb within layouts/application (3.6ms)
Rendered layouts/_messages.html.erb (0.6ms)
Completed 422 Unprocessable Entity in 1202ms (Views: 269.7ms | ActiveRecord: 11.5ms)
....below are my controller, models and views related to this form...
class AssignmentsController < ApplicationController
before_action :set_assignment, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token #TODO refactor this line to be very specific
# GET /assignments or /assignments.json
def index
#assignments = Assignment.date_range(params[:start]..params[:end])
end
# GET /assignments/1 or /assignments/1.json
def show
end
# GET /assignments/new
def new
add_shift
# #assignment.volunteer_shift.build
#my_url = {:action => "create", :id => params[:id]}
end
# GET /assignments/1/edit
def edit
end
# POST /assignments or /assignments.json
def create
# #assignment = Assignment.new(assignment_params)
create_shift
respond_to do |format|
if #assignment.save
format.html { redirect_to #assignment, notice: "Assignment was successfully created." }
format.json { render :show, status: :created, location: #assignment }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #assignment.errors, status: :unprocessable_entity }
end
end
end
def add_shift # FIXME: evil brought over from old app
ve = nil
if !params["id"].blank?
ve = VolunteerEvent.find_by_id(params["id"])
else
ve = VolunteerEvent.new
end
vs = ve.volunteer_shifts.new
vs.program = Program.find_by_name("intern")
# vs.slot_count = 1
vs.volunteer_event_id = ve.id if ve.id
vs.volunteer_event = ve
a = vs.assignments.new
a.volunteer_shift = vs
vs.stuck_to_assignment = true
vs.not_numbered = true
#assignments = vs.assignments = [a]
#referer = request.env["HTTP_REFERER"]
#my_url = {:action => "create_shift", :id => params[:id]}
#assignment = a
# binding.pry
# render :partial => 'assignments/new'
# render :partial => 'assignments/edit' #<--original
end
def create_shift # FIXME: evil brought over from original code base
# #fonso = #assignment.inspect
ve = nil
# Fixme: building volunteer shifts variable "vs" and associating with assignment
if !params["id"].blank?
ve = VolunteerEvent.find(params["id"])
else
if params["roster_id"].blank? || params["set_date"].blank?
ve = VolunteerEvent.new # won't save
else
ve = Roster.find_by_id(params["roster_id"]).vol_event_for_date(params["set_date"])
end
end
vs = ve.volunteer_shifts.new
vs.stuck_to_assignment = true
vs.not_numbered = true
#fixme: volunteer shifts variable "vs" and association with assignment end
# FIXME: vs.attributes=(params["assignment"]["volunteer_shift_attributes"]) # original needs to be rebuilt 4 this system
h0 = {"volunteer_task_type_id" => params["volunteer_task_type_id"]}
h1 = {"roster_id" => params["roster_id"]}
h2 = {"program_id" => params["program_id"]}
h3 = {"set_description" => params["set_description"]}
hash_arr = [h0,h1,h2,h3]
volunteer_shift_attributes = hash_arr.reduce { |acc, h| (acc || {}).merge h }
vs.attributes = volunteer_shift_attributes
#fixme: vs.attributes fix end
#FIXME: building variable - #assignments END
assignment = vs.assignments.new
vs = assignment.volunteer_shift
assignment.attributes = (assignment_params)
#assignments = [assignment]
#fixme: building variable - #assignments END
#FIXME: wtf is it and why is it?
vs.assignments = [assignment]
vs.set_values_if_stuck #fixme: <---- drill into this one
vs.assignments = []
binding.pry
#success = assignment.valid? && vs.save #fixme: <--------what was the valid? error here?
#assignment = assignment #fixme: <-----------------------#assignment is finally built here
# fixme: the above lines are merging params from one into the other in the old app.
# fixme: to create the new volunteer_shift.
if #success
vs = vs.reload
#assignment = a = vs.assignments.new
a.volunteer_shift = vs
# a.volunteer_shift_id = vs.id
a.attributes = (params["assignment"])
#assignments = vs.assignments = [a]
if !#success
vs.destroy
end
end
end
def update # ported over from old app
unless params[:assignment]
redirect_to :action => "index"
return
end
#my_url = {:action => "update", :id => params[:id]}
last_id = nil
begin
#assignments = params[:id].split(",").map{|x| last_id = x; Assignment.find(x)}
rescue ActiveRecord::RecordNotFound
flash[:jsalert] = "The assignment (##{last_id.to_i.inspect}) seems to have disappeared or never existed. It is possible somebody else has modified or deleted it."
rt = params[:assignment].delete(:redirect_to)
redirect_skedj(rt, "")
return
end
lv = params["lock_versions"]
ac = params["assigned_contacts"] || {}
#assigned_contacts = []
#replaced_contacts = []
ret = true
#assignments.each do |as|
as.lock_version = lv[as.id.to_s]
if as.lock_version_changed?
as.errors.add("lock_version", "is stale for this assignment, which means it has been edited by somebody else since you opened it, please try again")
ret = false
end
if as.contact_id && as.contact_id.to_s != params[:assignment][:contact_id].to_s
#assigned_contacts << as.contact
unless ac[as.contact_id.to_s] && ac[as.contact_id.to_s] == "replace"
as.errors.add("contact_id", "has been changed, please confirm below that the volunteer who is already assigned to the shift should be removed")
ret = false
else
#replaced_contacts << as.contact_id
end
end
end
rt = params[:assignment].delete(:redirect_to)
js_alert = nil
if ! ret
#assignment = Assignment.new
#assignment.volunteer_shift = #assignments.first.volunteer_shift
#assignment.attributes=(params[:assignment]) # .. ? .delete("volunteer_shift_attributes")
end
#assignments.each{|x|
if ret
#assignment = x
bc = x.contact_id
ret = !!(x.update_attributes(params[:assignment]))
if bc != x.contact_id and x.first_time_in_area?
alert = "#{x.contact.display_name} (##{x.contact_id}) has never logged hours for the #{x.volunteer_shift.volunteer_task_type.description} task type. Please remind the volunteer of the requirements for this area."
if x.volunteer_shift.volunteer_event and x.volunteer_shift.volunteer_event.notes and x.volunteer_shift.volunteer_event.notes.length > 0
alert += "\n\nSome suggested notes saved in the database for this event are:\n" + x.volunteer_shift.volunteer_event.notes
end
js_alert = alert
end
end
}
if ret && #assignment.contact and not #assignment.contact.is_old_enough?
msg = "This volunteer is not yet #{Default['minimum_volunteer_age']} years old (based on their saved birthday: #{#assignment.contact.birthday.to_s}).\nPlease remind the volunteer that they must have an adult with them to volunteer."
if js_alert == nil
js_alert = msg
else
js_alert = msg + "\n\n" + js_alert
end
end
flash[:jsalert] = js_alert if js_alert
if ret
flash[:notice] = 'Assignment was successfully updated.'
redirect_skedj(rt, #assignment.volunteer_shift.date_anchor)
else
#referer = rt
render :action => "edit"
end
end
# DELETE /assignments/1 or /assignments/1.json
def destroy
#assignment.destroy
# NOTE: comment original out 4 now
# respond_to do |format|
# format.html { redirect_to assignments_url, notice: "Assignment was successfully destroyed." }
# format.json { head :no_content }
# end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_assignment
#assignment = Assignment.find(params[:id])
end
# Only allow a list of trusted parameters through.
def assignment_params
#fixme: ,volunteer_shift_attributes: [:???, :???, :???] <--- insert this below?
params.require(:assignment).permit(:title, :date_range, :set_date, :date, :volunteer_shift_id, :contact_id, :start_time, :end_time, :start, :end, :attendance_type_id, :notes, :call_status_type_id, :closed, :lock_version, :color, :description)
# params.require(:assignment).permit(:title, :redirect_to, :set_date, :date_range, :contact_id, :start_time, :end_time, :start, :end, :attendance_type_id, :notes, :call_status_type_id, :closed, :lock_version, :color, volunteer_shift_attributes: [:volunteer_task_type_id,:roster_id,:program_id,:set_description,:set_date,:id,:destroy])
end
end
Model assignment
class Assignment < ApplicationRecord
# attr_accessor :volunteer_event ,:contact_id #why is this volunteer_event and not volunteer_shift???
belongs_to :volunteer_shift
has_one :volunteer_task_type, :through => :volunteer_shift, :source => :volunteer_task_type
belongs_to :contact ,optional: true
validates_presence_of :volunteer_shift #belongs_to takes care of this now
validates_associated :volunteer_shift
belongs_to :attendance_type
belongs_to :call_status_type
validates_presence_of :set_date, :if => :volshift_stuck #belongs_to takes care of this now??
accepts_nested_attributes_for :volunteer_shift, allow_destroy: true
delegate :set_date, :set_date=, :to => :volunteer_shift
delegate :set_description, :set_description=, :to => :volunteer_shift
has_one :contact_volunteer_task_type_count, lambda{||
{:conditions => 'contact_volunteer_task_type_counts.contact_id = #{defined?(attributes) ? contact_id : "assignments.contact_id"}', :through => :volunteer_shift, :source => :contact_volunteer_task_type_counts}
}
scope :date_range, lambda { |range|
joins(volunteer_shift: :volunteer_event)
.where(volunteer_shifts: { volunteer_events: { date: range } })
}
scope :is_after_today, lambda {||
{ :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) > ?', Date.today] }
}
scope :on_or_after_today, lambda {||
{ :conditions => ['(SELECT date FROM volunteer_events WHERE id = (SELECT volunteer_event_id FROM volunteer_shifts WHERE id = assignments.volunteer_shift_id)) >= ?', Date.today] }
}
scope :not_cancelled, -> { where('(attendance_type_id IS NULL OR attendance_type_id NOT IN (SELECT id FROM attendance_types WHERE cancelled = \'t\'))')}
scope :roster_is_limited_by_program, -> {where("roster_id IN (SELECT id FROM rosters WHERE limit_shift_signup_by_program = 't')").joins(:volunteer_shift)}
def real_programs
return [] unless self.volunteer_shift&.roster
return [] unless self.volunteer_shift.roster.limit_shift_signup_by_program
self.volunteer_shift.roster.skeds.select{|x| x.category_type == "Program"}.map{|x| x.name}
end
attr_accessor :attendance_type_id
# TODO: find all time_range_s methods and either pull out to DRY or give unique names
def time_range_s
return "" unless start_time and end_time
(start_time.strftime("%I:%M") + ' - ' + end_time.strftime("%I:%M")).gsub( ':00', '' ).gsub( ' 0', ' ').gsub( ' - ', '-' ).gsub(/^0/, "")
end
def description
return unless volunteer_shift
self.volunteer_shift.volunteer_event.date.strftime("%D") + " " + self.time_range_s + " " + self.slot_type_desc
end
def roster_title
return unless volunteer_shift
self.volunteer_shift.roster.name
end
def date
return unless volunteer_shift
volunteer_shift.date
end
#full calendar uses this method name....see the assignment.json.jbuilder
def event_date
return unless volunteer_shift
self.date
end
def contact_display
if self.closed
"(closed)"
elsif contact_id.nil?
return "(available)"
else
self.contact.display_name + "(#{self.voltask_count})"
end
end
before_validation :set_values_if_stuck
def set_values_if_stuck
return unless (volshift_stuck || volunteer_shift)
volunteer_shift.set_values_if_stuck(self)
end
after_destroy { |record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.destroy; else VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available; end}
after_save {|record| if record.volunteer_shift&.stuck_to_assignment; record.volunteer_shift.save; end}
after_save { |record| VolunteerShift.find_by_id(record.volunteer_shift_id).fill_in_available }
def volunteer_shift_attributes=(attrs)
return unless volunteer_shift
self.volunteer_shift.attributes=(attrs) # just pass it up
end
def volshift_stuck
return unless volunteer_shift
self.volunteer_shift&.stuck_to_assignment
end
#for fullcalendar
def all_day_event?
self.start_time == self.start_time.midnight && self.end_time == self.end_time.midnight ? true : false
end
end
model volunteer_shift
class VolunteerShift < ApplicationRecord
validates_presence_of :roster_id
validates_presence_of :end_time
validates_presence_of :start_time
has_many :assignments
belongs_to :volunteer_default_shift
belongs_to :volunteer_task_type
belongs_to :roster
belongs_to :volunteer_event
belongs_to :program
has_many :contact_volunteer_task_type_counts, :primary_key => 'volunteer_task_type_id', :foreign_key => 'volunteer_task_type_id' #:through => :volunteer_task_type
def validate
errors.add("end_time", "is before the start time") unless self.start_time && self.end_time && self.start_time < self.end_time
end
...
def set_description
self.description
end
def set_description=(desc)
self.description=(desc)
end
def set_date_set
#set_date_set
end
def set_date=(val)
#set_date_set = true
#set_date = val
end
def set_date
#set_date_set ? #set_date : self.volunteer_event.date
end
def set_values_if_stuck(assn_in = nil)
return unless self.stuck_to_assignment #<---it's a boolean in the database
assn = assn_in || self.assignments.first
return unless assn
self.start_time = assn.start_time
self.end_time = assn.end_time
return unless self.volunteer_event_id.nil? or self.volunteer_event.description.match(/^Roster #/)
return unless set_date_set <----SOMETHING BREAKS HERE on these two lines
roster = Roster.find_by_id(self.roster_id)
if roster and !(set_date == nil || set_date == "")
ve = roster.vol_event_for_date(set_date)
ve.save! if ve.id.nil?
self.volunteer_event = ve
self.volunteer_event_id = ve.id
else
if self.volunteer_event.nil?
self.volunteer_event = VolunteerEvent.new
end
end
end
def shift_display
time_range_s + ((!(self.description.nil? or self.description.blank?)) ? (": " + self.description) : "")
end
def time_range_s
return unless self.read_attribute(:start_time) and self.read_attribute(:end_time)
(self.my_start_time("%I:%M") + ' - ' + self.my_end_time("%I:%M")).gsub( ':00', '' ).gsub( ' 0', ' ').gsub( ' - ', '-' ).gsub(/^0/, "")
end
def my_start_time(format = "%H:%M")
read_attribute(:start_time).strftime(format)
end
def self._parse_time(time)
Time.mktime(2000, 01, 01, *time.split(":").map(&:to_i))
end
def my_start_time=(str)
write_attribute(:start_time, VolunteerShift._parse_time(str))
end
def my_end_time(format = "%H:%M")
read_attribute(:end_time).strftime(format)
end
def my_end_time=(str)
write_attribute(:end_time, VolunteerShift._parse_time(str))
end
def self.range_math(*ranges)
... # have to edit this post down
end
def fill_in_available
return if self.stuck_to_assignment #<-- it's a boolean in the database
Thread.current['volskedj_fillin_processing'] ||= []
if Thread.current['volskedj_fillin_processing'].include?(self.id)
return
end
begin
Thread.current['volskedj_fillin_processing'].push(self.id)
Assignment.where(volunteer_shift_id: self.id).select{|x| x.contact_id.nil? and !x.closed}.each{|x| x.destroy}
inputs = [[(self.read_attribute(:start_time)), (self.read_attribute(:end_time))]]
Assignment.where(volunteer_shift_id: self.id).select{|x| !x.cancelled?}.each{|x|
inputs.push([(x.start_time), (x.end_time)])
}
results = self.class.range_math(*inputs)
results.each{|x|
a = Assignment.new
a.volunteer_shift_id, a.start_time, a.end_time = self.id, x[0], x[1]
a.volunteer_shift = self
a.closed = self.volunteer_event.nowalkins
a.save!
}
ensure
Thread.current['volskedj_fillin_processing'].delete(self.id)
end
end
after_save :fill_in_available
def date
self.volunteer_event.date
end
def date_display
self.date.strftime('%A, %B %d, %Y').gsub( ' 0', ' ' )
end
def date_anchor
self.date ? self.date.strftime('%Y%m%d') : ''
end
def time_shift(val)
self.start_time += val
self.end_time += val
end
def left_method_name
[self.volunteer_task_type_id.nil? ? self.volunteer_event.description : self.volunteer_task_type.description, self.slot_number].select{|x| !x.nil?}.join(", ")
end
def left_unique_value
left_method_name
end
def description_and_slot
((self.volunteer_task_type_id || -1) * 1000) + (self.not_numbered ? 0 : self.slot_number)
end
def weekday
Weekday.find_by_id(self.date.strftime("%w"))
end
end
And the views
_new.html.erb <----- NOTE this name...this is the modal
<div class="modal fade" id="add_event">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<div class="col-sm-12 left ">
<h4 class="modal-title">Add New Assignment - _new.html.erb</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
</div>
<%=#my_url %>
<%#= render 'assignments/form', assignment: #assignment %>
</div>
</div>
</div>
_form.html.erb
<!--This is NEW action form-->
<%= form_for #assignment, :url => #my_url, remote: true do |f| %>
<!-- #FIXME need a fields_for 4 the volunteer_event-->
<div class="">
<div class="modal-body d-flex">
<div class="col-sm-8 border-right">
<section id="location-date-time-notes" class="flex">
<% if #assignment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#assignment.errors.count, "error") %> prohibited this assignment from being saved:</h2>
<ul>
<% #assignment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<!--VOLUNTEER SHIFT-->
<!--TODO: make this a partial under field_for-->
<%= f.fields_for :volunteer_event do |builder| %>
<%= render 'assignments/volunteer_shift_fields', vs: builder %>
<% end %>
<!--TODO: Volunteer Shift end -->
<div id="time-row" class="d-flex flex-row">
<label for="assignment_time" class="col-sm-3 p-2">
<i class="fa fa-clock-o fa-lg" aria-hidden="true"></i> Time:
</label>
<div class="col- p-2">
<div class="myStartTime" id="start_time_<%= #assignment.id %>">
<%= f.time_select :start_time %>
</div>
</div>
<div class="col- p-2"><i class="fa fa-arrows-h fa-lg" aria-hidden="true"></i></div>
<div class="col-sm-3 p-2">
<div class="myEndTime" id="end_time_<%= #assignment.id %>">
<%= f.time_select :end_time %>
</div>
</div>
</div>
<div class="d-flex flex-row">
<label for="assignment_notes" class="col-sm-3 p-2">
<i class="fa fa-clipboard fa-lg" aria-hidden="true"></i> Notes:
</label>
<div class="col-sm-9 p-2">
<div class="d-flex flex-row">
<span> Notes only get saved if a contact is assigned the shift, and get removed when the contact is removed from the shift.</span>
<div class="">
<%= f.label :notes %>
<%= f.text_area :notes %>
</div>
</div>
</div>
</div>
</section>
</div>
<div class="col-sm-4">
<!-- Contact Section-->
<div id="contact_section">
<% if #assigned_contacts && #assigned_contacts.length > 0 %>
<h2>Previously Assigned Contacts</h2>
<% #assigned_contacts.each do |c| %>
<%= label_tag "assigned_contacts[#{c.id}]", "Are you sure you want to remove the currently scheduled volunteer, #{c.display_name} (##{c.id}), from the assignment(s)?" %>
<%= check_box_tag "assigned_contacts[#{c.id}]", "replace", #replaced_contacts.include?(c.id) %>
<% end %>
<% end %>
<input id="contact_element_prefix" name="contact_element_prefix" type="hidden" value="contact">
<div class="name large flex-row">
<%= f.label :contact_id %><%= f.text_field :contact_id %>
</div>
<div id="display-contact" class="d-flex flex-row">
<p>_form</p>
<% if f.object.contact_id %>
<%= render partial: 'contacts/contact_display', locals: { contact:f.object.contact} %>
<% else %>
<div>no contact - _form.html called</div>
<%#= link_to 'Show Contact', contact_path(f.object.contact_id), remote: true %>
<% end %>
</div>
<!-- FIXME: replace this logic stack with AJAX-->
<%#= contact_field("#obj", "contact_id",
:locals => {:options => {
:object_name => f.object_name.to_s,
:field_name => 'contact_id',
:on_display => 'display_disciplinary_notes(); display_contact_notes();'
}}
) %>
<%= f.label :closed, "Is this slot closed?" %>
<%= f.check_box :closed %>
<!--Contact Section END-->
<!--Attendance / Call Status End-->
<% if f.object.id && f.object.contact_id %>
<div class="flex-row">
<div class="col-25"><label for="assignment_attendance_type_id">Attendance:</label></div>
<div class="col-75"><%= select(f.object_name,
"attendance_type_id",
AttendanceType.all.sort_by(&:id).collect {|p| [ p.name, p.id ] },
:include_blank => true) %></div>
</div>
<div class="flex-row">
<div class="col-25"><label for="assignment_call_status_type_id">Call status:</label></div>
<div class="col-75"><%= select(f.object_name,
"call_status_type_id",
([["not called yet", ""]] + CallStatusType.all.sort_by(&:id).collect {|p| [ p.name, p.id ] }),
:include_blank => false) %></div>
</div>
<% end %>
<!-- Attendance / Call Status End-->
<!-- LOCK VERSION-->
<div class="flex-row">
<div class="col-25">
<%= f.label :lock_version %>
</div>
<div class="col-75">
<%= f.number_field :lock_version %>
</div>
</div>
<!-- LOCK end-->
</div>
</div>
</div>
<div class="modal-footer d-flex justify-content-between">
<div class="edit_icons d-flex flex-row">
<div class="d-flex flex-column">
</div>
<div class="d-flex flex-column">
<%#= link_to '<i class="fa fa-pencil-square-o fa-lg" aria-hidden="true"></i>Edit'.html_safe, edit_assignment_path, remote: true%>
</div>
</div>
<div>
<button type="button" class="btn btn-secondary mr-2" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary"><%= f.submit "Submit" %></button>
</div>
</div>
</div>
<% end %>
_volunteer_shift_fields.html.erb
<!--<div class="name large flex-row">-->
<%#= vs.label :volunteer_shift %>
<!--</div>-->
<div id="volunteer_shift" class="d-flex flex-row">
<div class="col-sm-12 p-2">
<div id="volunteer_shift" class="text-right">
<!-- old if: if class is assignment show volunteer shift else show default shift -->
<!-- we need default shift here...NO assignment is attached-->
<div class="field">
<%= vs.label :volunteer_task_type_id %>
<%= select_tag 'volunteer_task_type_id', options_from_collection_for_select([VolunteerTaskType.new(:description => ""), VolunteerTaskType.instantiables.effective_on(Date.today)].flatten, "id", "description") %>
</div>
<div class="field">
<%= vs.label :roster_id %>
<%= select_tag 'roster_id', options_from_collection_for_select([Roster.new(:name => ""), Roster.all].flatten, "id", "name") %>
</div>
<div class="field">
<%= vs.label :program_id %>
<%= select_tag 'program_id', options_from_collection_for_select([Program.new(:name => ""), Program.where(:volunteer => true)].flatten, "id", "name")%>
</div>
<div class="field">
<%= vs.label :set_description %>
<%= text_field(:set_description, nil) %>
</div>
<div class="field">
<%= vs.label :set_date, "Date" %>
<%= text_field(:set_date, nil) %>
</div>
</div>
</div>
</div>
assignments/new.html.erb
Why is it coming here????
I just want the modal "_new.html.erb" to disapear after the form post but rails is sending me here. And I am confused as to why (something simple I'm sure)
<%= render 'form_old', assignment: #assignment %> <---this old form no longer exist
<!--
<%= link_to 'Back', assignments_path %>
volunteer_shift method set_values_if_stuck (see above also)
def set_values_if_stuck(assn_in = nil)
...
return unless self.volunteer_event_id.nil? or self.volunteer_event.description.match(/^Roster #/)
binding.pry
return unless set_date_set #fixme:<--- pry me
roster = Roster.find_by_id(self.roster_id)
...
end
Somewhat straightforward to me if I'm not mistaken your question as to "why _new is rendered".
def create
# #assignment = Assignment.new(assignment_params)
create_shift
respond_to do |format|
if #assignment.save
format.html { redirect_to #assignment, notice: "Assignment was successfully created." }
format.json { render :show, status: :created, location: #assignment }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #assignment.errors, status: :unprocessable_entity }
end
end
end
Here, whatever happens in create_shift method, #assignment is being saved; if successfully, then render the :show page, if not, :new page, which by default _new.html.erb in this code.
As to "why the save fails", you could print or use one of those pry gems to see #assignment.errors right before #assignment.save.

Sorting multiple models in one controller

I am using Ruby on Rails 5.2.3 and Mongoid 7.0
I need to be able to sort multiple models (Item and Text) in one cotroller.
Now only Item or Text is sorted, it is necessary that Position was set in relation to each other.
class UsersController < ApplicationController
def sort
params[:item].each_with_index do |id, index|
Item.where(id: id).update_all(position: index + 1)
end
head :ok
end
def admin
#user_items = #user.user_feed
end
end
admin.html.erb
<div id="items" data-url="<%= sort_users_path %>">
<%= render partial: 'users/user_item', collection: #user_items %>
</div>
_user_item.html.erb
<% if user_item[:title].present? %>
<div id="item_<%= user_item[:id] %>">
<%= user_item[:position] %>
</div>
<% end %>
<% if user_item[:text].present? %>
<div id="item_<%= user_item[:id] %>">
<%= raw user_item[:position] %>
</div>
<% end %>
User.rb
def user_activity
activity_items = []
items.each do |item|
activity_item = {}
activity_item[:id] = item.id
activity_item[:url] = item
activity_item[:title] = item.title
activity_item[:position] = item.position
activity_item[:item_link] = item.url
activity_items << activity_item
end
texts.each do |text|
activity_item = {}
activity_item[:id] = text.id
activity_item[:url] = text
activity_item[:text] = text.text
activity_item[:position] = text.position
activity_items << activity_item
end
activity_items.sort_by! { |activity_item| activity_item[:position] }
activity_items
end
def user_feed
activity_items = user_activity
activity_items.sort_by! { |activity_item| activity_item[:position] }
activity_items
end
Just needed to add Text.where(id: id).update_all(position: index + 1)
def sort
params[:item].each_with_index do |id, index|
Item.where(id: id).update_all(position: index + 1)
Text.where(id: id).update_all(position: index + 1)
end
head :ok
end

ActionView::Template::Error (undefined method `strip!' for nil:NilClass)

It seems I'm running into this error when I insert more than 100,000 records. I know it can support way more than that. The error is below and the code for the related classes.
2015-07-01 08:14:24.512:INFO:/:Started GET "/search?type=digital_object" for 129.118.15.44 at 2015-07-01 08:14:24 -0500|
2015-07-01 08:14:24.512:INFO:/:Processing by SearchController#search as HTML|
2015-07-01 08:14:24.512:INFO:/: Parameters: {"type"=>"digital_object"}|
Jul 01, 2015 8:14:24 AM org.apache.solr.core.SolrCore execute
INFO: [collection1] webapp= path=/select params={facet=true&sort=title_sort+asc&facet.limit=100&qf=four_part_id^3+title^2+finding_aid_filing_title^2+fullrecord&wt=json&rows=10&defType=edismax&pf=four_part_id^4&start=0&q=*:*&facet.field=repository&facet.field=primary_type&facet.field=subjects&facet.field=source&facet.field=linked_agent_roles&fq=types:("digital_object")&fq=-exclude_by_default:true&fq=publish:true} hits=203799 status=0 QTime=15
2015-07-01 08:14:24.590:INFO:/: Rendered G:/archivesspace/plugins/vva/public/views/search/_components_switch.html.erb (15.0ms)|
2015-07-01 08:14:24.590:INFO:/: Rendered search/_filter.html.erb (0.0ms)|
2015-07-01 08:14:24.606:INFO:/: Rendered search/_pagination_summary.html.erb (16.0ms)|
2015-07-01 08:14:24.637:INFO:/: Rendered search/_inline_results.html.erb (47.0ms)|
2015-07-01 08:14:24.637:INFO:/: Rendered search/results.html.erb within layouts/application (62.0ms)|
2015-07-01 08:14:24.653:INFO:/:Completed 500 Internal Server Error in 141.0ms|
2015-07-01 08:14:24.653:INFO:/:|ActionView::Template::Error (undefined method `strip!' for nil:NilClass):|
17: <% elsif result["primary_type"] === "repository" %>|
18: <%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>|
19: <% else %>|
20: <%= link_to title_or_finding_aid_filing_title( result ) , :controller => :records, :action => result["primary_type"], :id => id, :repo_id => repo_id %>|
21: <% end %>|
22: </h3>|
23: <div class="result-summary">| app/helpers/application_helper.rb:22:in `title_or_finding_aid_filing_title'|
app/views/search/_inline_results.html.erb:20:in `_app_views_search__inline_results_html_erb___996910774_15116'|
app/views/search/_inline_results.html.erb:5:in `_app_views_search__inline_results_html_erb___996910774_15116'|
app/helpers/application_helper.rb:134:in `render_aspace_partial'|
app/views/search/results.html.erb:13:in `_app_views_search_results_html_erb__332589766_15048'|
app/controllers/search_controller.rb:21:in `search'|
app/controllers/search_controller.rb:20:in `search'|||
_inline_results.html.erb
<div class="search-results">
<% if search_data.results? %>
<%= render_aspace_partial :partial => "search/pagination_summary", :locals => {:search_data => search_data} %>
<ul class="results-list">
<% search_data['results'].each do |result| %>
<%
id = JSONModel(result["primary_type"]).id_for(result['uri'])
repo_id = JSONModel(:repository).id_for(JSONModel.repository_for(result['uri']),{}, true)
%>
<li class="result">
<h3>
<%= icon_for result["primary_type"] %>
<% if result["primary_type"] === "subject" %>
<%= link_to result["title"], {"filter_term" => search_data.facet_query_string("subjects", result["title"])} %>
<% elsif ["agent_person", "agent_software", "agent_family", "agent_corporate_entity"].include?(result["primary_type"]) %>
<%= link_to result['title'], :controller => :records, :action => :agent, :id => id, :agent_type => result["primary_type"] %>
<% elsif result["primary_type"] === "repository" %>
<%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>
<% else %>
<%= link_to title_or_finding_aid_filing_title( result ) , :controller => :records, :action => result["primary_type"], :id => id, :repo_id => repo_id %>
<% end %>
</h3>
<div class="result-summary">
<%= render_aspace_partial :partial => "search/result_summary_#{result["primary_type"]}", :locals => {:obj => result} %>
</div>
</li>
<% end %>
</ul>
<%= render_aspace_partial :partial => "search/pagination", :locals => {:search_data => search_data} %>
<% else %>
<p class="alert alert-info">
<%= I18n.t("search_results.no_results") %></em>.
</p>
<% end %>
</div>
search_controller.rb
require 'advanced_query_builder'
class SearchController < ApplicationController
DETAIL_TYPES = ['accession', 'resource', 'archival_object', 'digital_object',
'digital_object_component', 'classification',
'agent_person', 'agent_family', 'agent_software', 'agent_corporate_entity']
VIEWABLE_TYPES = ['agent', 'repository', 'subject'] + DETAIL_TYPES
FACETS = ["repository", "primary_type", "subjects", "source", "linked_agent_roles"]
def search
set_search_criteria
#search_data = Search.all(#criteria, #repositories)
#term_map = params[:term_map] ? ASUtils.json_parse(params[:term_map]) : {}
respond_to do |format|
format.html { render "search/results" }
format.js { render_aspace_partial :partial => "search/inline_results", :content_type => "text/html", :locals => {:search_data => #search_data} }
end
end
def advanced_search
set_advanced_search_criteria
#search_data = Search.all(#criteria, #repositories)
render "search/results"
end
def repository
set_search_criteria
if params[:repo_id].blank?
#search_data = Search.all(#criteria.merge({"facet[]" => [], "type[]" => ["repository"]}), {})
return render "search/results"
end
#repository = #repositories.select{|repo| JSONModel(:repository).id_for(repo.uri).to_s === params[:repo_id]}.first
#breadcrumbs = [
[#repository['repo_code'], url_for(:controller => :search, :action => :repository, :id => #repository.id), "repository"]
]
#search_data = Search.repo(#repository.id, #criteria, #repositories)
render "search/results"
end
private
def set_search_criteria
#criteria = params.select{|k,v|
["page", "q", "type", "sort",
"filter_term", "root_record", "format"].include?(k) and not v.blank?
}
#criteria["page"] ||= 1
#criteria["sort"] = "title_sort asc" unless #criteria["sort"] or #criteria["q"] or params["advanced"].present?
if #criteria["filter_term"]
#criteria["filter_term[]"] = Array(#criteria["filter_term"]).reject{|v| v.blank?}
#criteria.delete("filter_term")
end
if params[:type].blank?
#criteria['type[]'] = DETAIL_TYPES
else
#criteria['type[]'] = Array(params[:type]).keep_if {|t| VIEWABLE_TYPES.include?(t)}
#criteria.delete("type")
end
#criteria['exclude[]'] = params[:exclude] if not params[:exclude].blank?
#criteria['facet[]'] = FACETS
end
def set_advanced_search_criteria
set_search_criteria
terms = (0..2).collect{|i|
term = search_term(i)
if term and term["op"] === "NOT"
term["op"] = "AND"
term["negated"] = true
end
term
}.compact
if not terms.empty?
#criteria["aq"] = AdvancedQueryBuilder.new(terms, :public).build_query.to_json
#criteria['facet[]'] = FACETS
end
end
def search_term(i)
if not params["v#{i}"].blank?
{ "field" => params["f#{i}"], "value" => params["v#{i}"], "op" => params["op#{i}"], "type" => "text" }
end
end
end
application_helper.rb
module ApplicationHelper
def include_theme_css
css = ""
css += stylesheet_link_tag("themes/#{ArchivesSpacePublic::Application.config.public_theme}/bootstrap", :media => "all")
css += stylesheet_link_tag("themes/#{ArchivesSpacePublic::Application.config.public_theme}/application", :media => "all")
css.html_safe
end
def set_title(title)
#title = title
end
def title_or_finding_aid_filing_title(resource)
if resource["finding_aid_filing_title"] && !resource["finding_aid_filing_title"].nil? && resource["finding_aid_filing_title"].length > 0
title = resource["finding_aid_filing_title"]
elsif resource["title"] && !resource["title"].nil?
title = resource["title"]
else
title = resource["display_string"]
end
MixedContentParser::parse(title, url_for(:root))
end
def icon_for(type)
"<span class='icon-#{type}' title='#{I18n.t("#{type}._singular")}'></span>".html_safe
end
def label_and_value(label, value)
return if value.blank?
label = content_tag(:dt, label)
value = content_tag(:dd, value)
label + value
end
def i18n_enum(jsonmodel_type, property, value)
return if value.blank?
property_defn = JSONModel(jsonmodel_type).schema["properties"][property]
return if property_defn.nil?
if property_defn.has_key? "dynamic_enum"
enum_key = property_defn["dynamic_enum"]
#return "enumerations.#{enum_key}.#{value}"
I18n.t("enumerations.#{enum_key}.#{value}", :default => value)
else
I18n.t("#{jsonmodel_type}.#{property}_#{value}", :default => value)
end
end
def params_for_search(opts = {})
search_params = {
:controller => :search,
:action => :search
}
search_params["filter_term"] = Array(opts["filter_term"] || params["filter_term"]).clone
search_params["filter_term"].concat(Array(opts["add_filter_term"])) if opts["add_filter_term"]
search_params["filter_term"] = search_params["filter_term"].reject{|f| Array(opts["remove_filter_term"]).include?(f)} if opts["remove_filter_term"]
search_params["sort"] = opts["sort"] || params["sort"]
search_params["q"] = opts["q"] || params["q"]
search_params["format"] = params["format"]
search_params["root_record"] = params["root_record"]
search_params["agent_type"] = params["agent_type"]
search_params["page"] = opts["page"] || params["page"] || 1
if opts["type"] && opts["type"].kind_of?(Array)
search_params["type"] = opts["type"]
else
search_params["type"] = opts["type"] || params["type"]
end
search_params["term_map"] = params["term_map"]
# retain any advanced search params
advanced = (opts["advanced"] || params["advanced"])
search_params["advanced"] = advanced.blank? || advanced === 'false' ? false : true
search_params[:action] = :advanced_search if search_params["advanced"]
(0..2).each do |i|
search_params["v#{i}"] = params["v#{i}"]
search_params["f#{i}"] = params["f#{i}"]
search_params["op#{i}"] = params["op#{i}"]
end
search_params.reject{|k,v| k.blank? or v.blank?}
end
def set_title_for_search
title = I18n.t("actions.search")
if #search_data
if params[:type] && !#search_data.types.blank?
title = "#{I18n.t("search_results.searching")} #{#search_data.types.join(", ")}"
end
facets_to_display = []
if #search_data.query?
facets_to_display << #search_data.facet_label_for_query
end
if #search_data.filtered_terms?
facets_to_display << #search_data[:criteria]["filter_term[]"].collect{|filter_term| #search_data.facet_label_for_filter(filter_term)}
end
if facets_to_display.length > 0
title += " | #{facets_to_display.join(", ")}"
end
end
set_title(title)
end
def truncate(string, length = 50, trailing = '…')
return string if string.length < length
"#{string[0..50]}#{trailing}".html_safe
end
# See: ApplicationController#render_aspace_partial
def render_aspace_partial(args)
defaults = {:formats => [:html], :handlers => [:erb]}
return render(defaults.merge(args))
end
def proxy_localhost?
AppConfig[:frontend_proxy_url] =~ /localhost/
end
end
I got it figured out. Looks like some of the data imported had blank titles "". By updating them it was able to work.
The error is in your _inline_results.html.erb...
<% elsif result["primary_type"] === "repository" %>
<%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>
the error is that the result['title'] is nil. so, add this line of code....
<% elsif result["primary_type"] === "repository" %>
<% if !result['title'].blank? %>
<%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>
<% end %>

NoMethodError in Lines#show

UPDATE: The answer bellow is correct. Just wanted to update what I did to solve the problem.
First I had to delete all my previous lines in the rails console.
Then I used the bye bug gem in my lines controller at the bottom of the create method to discover where the next bug occurred. I created a test line that I needed to delete again. so I ran
Line.last.delete in console.
This is the way my lines controller create method looks now (working no bugs)
def create
if user_signed_in?
#line = Line.create(line_params)
if #line
if params[:line][:previous_line_id].empty?
#line.story = Story.create
#line.save
else
#line.story = #line.previous_line.story
#line.save
end
redirect_to line_path(#line)
else
flash[:error] = #line.errors
redirect_to line_path(Line.find(params[:line][:previous_line_id]))
end
else
Finally I ran #Lines.each { |line| line.update.attribute(:story_id: 3)}
This gave the necessary association between lines and story.
ORIGINAL POST BELLOW.
I'm getting this error in my rails app. I think that when I create a new line or start a story, it doesn't automatically add it to a story object. I've listed my show.html.erb file as well as my lines controller.rb file.
What am I missing? How do I get the controller to add data to the story object correctly?
Thanks!
I added a few lines of code to my lines controller:
class LinesController < ApplicationController
def new
params[:previous_line_id].nil? ? #line = Line.new : #line = Line.find(params[:previous_line_id]).next_lines.create
#lines = #line.collect_lines
#ajax = true if params[:ajax]
render :layout => false if params[:ajax]
if #line.previous_line
#line.update_attribute(:story_id, #line.previous_line.story.id)
else
story = Story.create
#line.story = story
#line.save
end
end
def create
if user_signed_in?
#line = Line.create(line_params)
if #line
redirect_to line_path(#line)
else
flash[:error] = #line.errors
redirect_to line_path(Line.find(params[:line][:previous_line_id]))
end
else
flash[:error] = "Please sign in or register before creating a line!"
unless params[:line][:previous_line_id].empty?
redirect_to line_path(Line.find(params[:line][:previous_line_id]))
else
redirect_to root_path
end
end
end
# params[:id] should correspond to the first line of the story.
# if params[:deeper_line_id] is not nil, that means that they want to render up to the nested line id
def show
#lines = Line.find(params[:id]).collect_lines
#next_lines = #lines.last.next_lines.ranked
#lines.last.update_attribute(:score, #lines.last.score + 1)
end
def select_next
#line = Line.find(params[:id])
#line.update_attribute(:score, #line.score + 1)
#lines = [#line]
#next_lines = #line.next_lines.ranked
render :layout => false
end
def send_invite
if user_signed_in?
UserInvite.send_invite_email(current_user,Line.find(params[:id]), params[:email]).deliver
flash[:notice] = "Your invite was sent!"
else
flash[:error] = "Please sign in"
end
redirect_to Line.find(params[:id])
end
private
def line_params
params.require(:line).permit(:text, :previous_line_id, :user_id)
end
end
I added these lines to the controller pictured above
if #line.previous_line
#line.update_attribute(:story_id, #line.previous_line.story.id)
else
story = Story.create
#line.story = story
#line.save
end
Here is my show.html.erb file
<div class="row">
<div class="col-lg-2">
</div>
<div class="box-container col-lg-7 ">
<div id="story" class="box">
<% #lines.each do |line| %>
<span class="story-line" data-id="<%=line.id%>"><%= link_to line.text, '#', :class=>"story-line" %></span>
<% end %>
</div>
<div id="next-steps">
<%= render 'next_steps' %>
</div>
<span style="font-size:.9em; margin-bottom:15px; display:block;">*If the links don't work, try refreshing.</span>
</div>
<div class="col-lg-2" style="padding-right:25px;">
<%= render 'invite' %>
Your Fellow Collaborators: <br />
<div class="collaborators">
<% #lines.last.story.collaborators.uniq.each do |collaborator| %>
<%= link_to profile_path(:id => collaborator.id) do %>
<%= image_tag collaborator.profile_image_uri, :class => "prof-icon" %>
<% end %>
<% end %>
</div>
Story model
class Story < ActiveRecord::Base
has_many :lines
has_and_belongs_to_many :collaborators, :class_name => "User", :join_table => "collaborators_stories", :association_foreign_key => :collaborator_id
def first_line
self.lines.first_lines.first_lines.first
end
end
Here is my lines.rb file
class Line < ActiveRecord::Base
scope :first_lines, -> { where previous_line_id: nil}
scope :ranked, -> { order("score + depth DESC")}
belongs_to :user
belongs_to :story
belongs_to :previous_line, :class_name => "Line", :foreign_key => "previous_line_id"
has_many :next_lines, :class_name => "Line", :foreign_key => "previous_line_id"
validates_presence_of :text
after_create :update_depths
def update_depths
line = self.previous_line
while !line.nil?
line.update_attribute(:depth, line.depth + 1)
line = line.previous_line
end
end
def first_line
line = self
while !line.previous_line.nil?
line = line.previous_line
end
line
end
def collect_lines
line = self
lines = [self]
while !line.previous_line.nil?
lines.unshift(line.previous_line)
line = line.previous_line
end
lines
end
end
Problem is orphaned lines in your database. Look for them and associate it to a story, or delete it:
How to find orphaned records:
http://antonzolotov.com/2013/01/26/how-to-find-and-delete-orphaned-records-with-ruby-on-rails.html
Then review the create method to ensure a line should be part of a story:
#short example review activerecord relations
#story = Story.find(params[:story_id])
story.lines.create(line_params)
That should work.
EDIT:
def self.find_orphan_ids
Lines.where([ "user_id NOT IN (?) OR story_id NOT IN (?)", User.pluck("id"), Story.pluck("id") ]).destroy_all
end

Rails exporting xls using link_to format

Hello everybody who likes RAILS, i have a problem i'm trying to export by "ejecutive_id" to XLS but i'm not doing the correct code,
-I created a select box where i can select all my ejecutives.
-I created another select box where i can select by status_id.
-I selected 1 ejecutive for example "Mogan" (ejecutive_id = 1)
-I selected 1 status form example "active" (status_id = 0 )
-After selecting both select boxes i click on "SEARCH"
-After doing SEARCH i'm getting my results (#list_policies this value in my code is before respond format)
Here is my controller
****PROJECT/APP/CONTROLLER/policy_managment/policy.rb********
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#search_ejecutive = params[:search_ejecutive]
#search_status = params[:status_id]
#list_ejecutives_comision = Ejecutive.find(:all)
#list_policies_search = Policy.deleted_is(0)
if params[:search_ejecutive].to_i!=0
#list_policies_search = #list_policies_search.ejecutive_id_is(#search_ejecutive)
end
if !params[:status_id].blank?
if params[:status_id].to_i != 3
#list_policies_search = #list_policies_search.state_is(params[:status_id])
end
else
#list_policies_search = #list_policies_search.state_is(0)
end
#status_id = params[:status_id]
if !#search_dependent_dni.blank?
if #list_dependents.blank?
#list_dependents = Dependent.id_gt(0)
end
#list_dependents = #list_dependents.num_document_is(#search_dependent_dni)
list_dependencies = []
#list_dependents.each do |dependent|
list_dependency_dependents = Dependency.find(:all, :conditions => { :dependent_id => dependent.id })
list_dependency_dependents.each do |dependency|
list_dependencies << dependency
end
end
policy_ids = []
list_dependencies.each do |dependency|
policy_ids << dependency.policy_id.to_i
end
end
#list_policies_search = #list_policies_search.deleted_is(0)
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
#results = #list_policies_search.find(:all,:conditions=> { :ejecutive_id => #search_ejecutive })
respond_to do |format|
format.html
format.xls
format.js {
render :update do |page|
page.replace_html 'table', :partial => 'table2'
end
}
end
end
end
Here maybe could be the problem,also those are my links where i can export
*********HERE IS MY VIEW***********
<% form_remote_tag :url=>{:action=>"generate_print_ejecutive_comercial"},:before=>"load_close('loading_search')",:success=>"load_off('loading_search')" do -%>
<label>EJECUTIVES:</label>
<%= select_tag 'search_ejecutive',"<option value=\"\">Select</option>"+options_for_select(#list_ejecutives_comision.collect {|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]})%>
</span>
<label>STATUS :</label>
<%= select_tag "status_id","<option value=\"3\">ALL</option>"+options_for_select([["active",0],["cancel",1],["no cancel ",2]],0) %>
</span>
<input name="Buscar" value="SEARCH" type="submit" /><span id="loading_search"></span>
<% end %>
#HERE WITH THOSE LINKS I'M EXPORTING ONLY MY FIRST 10 VALUES
<%= link_to("Export Excel","http://localhost:3000/policy_management/policy/generate_print_ejecutive/generate_print_ejecutive_comercial.xls")%>
<%= link_to "Export XLS",:controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial",:format=>"xls" %>
<%= link_to 'PRINT PDF', :controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial", :format=>"pdf" %>
I'm exporting my partial view and it depends of this
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
Here is my partial view and i'm using #list_policies
********************PARTIAL VIEW THAT I WANT TO EXPORT*********
<table>
<% #list_policies.each do |policy| %>
<tr>
<td><div class="nobreak"><%= policy.num_policy%></div></td>
<td><div class="nobreak">
<% if !policy.ejecutive.blank? %>
<%= policy.ejecutive.name %><%= policy.ejecutive.lastname1 %><%= policy.ejecutive.lastname2 %>
<% end %></div>
</td>
<td><div class="nobreak"><%= policy.str_state%></div></td>
</tr>
</table>
Seems that i need to add some params to my links_to....format.... i don't know what to add
Somebody can check this code?
It seems like using an options hash to dynamically build your query might be easier / cleaner. I would do it like this:
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#list_ejecutives_comision = Ejecutive.find(:all)
policy_options = {:deleted => false}
policy_options = policy_options.merge({:ejecutive_id => params[:search_ejecutive]}) unless params[:search_ejecutive].blank?
policy_options = policy_options.merge({:state => params[:status_id]}) unless params[:status_id].blank? and (params[:status_id] != 3)
#list_policies_search = Policy.all(policy_options)
if !#search_dependent_dni.blank?
if #list_dependents.blank?
#list_dependents = Dependent.id_gt(0)
end
#list_dependents = #list_dependents.num_document_is(#search_dependent_dni)
list_dependencies = []
#list_dependents.each do |dependent|
list_dependency_dependents = Dependency.find(:all, :conditions => { :dependent_id => dependent.id })
list_dependency_dependents.each do |dependency|
list_dependencies << dependency
end
end
policy_ids = []
list_dependencies.each do |dependency|
policy_ids << dependency.policy_id.to_i
end
end
#list_policies = #list_policies_search.paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html
format.xls
format.js {
render :update do |page|
page.replace_html 'table', :partial => 'table2'
end
}
end
end
end

Resources