Sunspot rails, highlighting with Disjunctions and conjunctions - ruby-on-rails

I'm implementing a full text search with sunspot, in which I store the text fields in order to get highlighted results. When it's just a fulltext it works fine without conjunctions, but when you have to put conjunctions it doesn't show up, it does the search fine, but the highlighting doesn't show up.
search model code:
def search
#search = Sunspot.new_search(DigitalEntity)
build_fields_searchs_search
#search.execute
end
def build_fields_searchs_search
object = self
#search.build do
any do
object.fields_searchs.select { |x| x.conjunction == 'or' }.each do |fields_search|
adjust_solr_params do |params|
if params[:q].present? && fields_search.conjunction == 'not'
params[:q] = params[:q].sub('OR _query', 'OR NOT _query')
end
end
if (fields_search.filter == 'begins') && fields_search.discovery_field
with(fields_search.discovery_field.identifier.to_sym).starting_with(fields_search.value)
else
fulltext fields_search.value do
highlight title: true
highlight description: true
highlight coverage: true
highlight fulltext: true
fields fields_search.discovery_field.identifier.to_sym if fields_search.discovery_field
minimum_match(1) if fields_search.filter == 'contains'
boost(2.0) { with(:users_email_bookmark, user.email) } if user
end
end
if fields_search.start_date && !fields_search.end_date
with(:date).greater_than_or_equal_to(fields_search.start_date)
elsif !fields_search.start_date && fields_search.end_date
with(:date).less_than_or_equal_to(fields_search.end_date)
elsif fields_search.start_date && fields_search.end_date
with(:date).between(fields_search.start_date..fields_search.end_date)
end
end
all do
object.fields_searchs.reject { |x| x.conjunction == 'or' }.each do |fields_search|
if fields_search.filter == 'exactly' && !fields_search.value.match('"')
fields_search.value = '"' + fields_search.value + '"'
end
adjust_solr_params do |params|
if params[:q].present? && fields_search.conjunction == 'not'
params[:q] = params[:q].sub('AND _query', 'AND NOT _query')
end
end
if (fields_search.filter == 'begins') && fields_search.discovery_field
with(fields_search.discovery_field.identifier.to_sym).starting_with(fields_search.value)
else
fulltext object.fields_searchs.value do#pluck(:value).join(" AND ") do
highlight :title
highlight :description
highlight :coverage
highlight :fulltext
highlight :contributor
fields fields_search.discovery_field.identifier.to_sym if fields_search.discovery_field
minimum_match(1) if fields_search.filter == 'contains'
boost(2.0) { with(:users_email_bookmark, user.email) } if user
end
end
if fields_search.start_date && !fields_search.end_date
with(:date).greater_than_or_equal_to(fields_search.start_date)
elsif !fields_search.start_date && fields_search.end_date
with(:date).less_than_or_equal_to(fields_search.end_date)
elsif fields_search.start_date && fields_search.end_date
with(:date).between(fields_search.start_date..fields_search.end_date)
end
end
end
end
end
end
searches helper:
def show(identifier, hit, opts = { sep: ', ' })
return '' unless hit
if hit.highlight(identifier)
highlights_for(identifier, hit)
else
raw(content(hit.stored(identifier), separator: opts[:sep], max_length: opts[:max_length])) unless(identifier == :fulltext)
end
end
def highlights_for(identifier, hit)
output = ''
hit.highlights(identifier).each do |h|
output += h.format { |word| "<span style='background-color: #eee5d5;color: #9E2D37;'>#{word}</span>" }
end
raw(output)
end
view code
<div class="content">
<h4 class="title">
<%= link_to link_url, remote: remote_link, style: "color: black !important", id: "item-#{item.primary_key}" do %>
<% if item.stored(:title) %>
<% title = item.stored(:title).first %>
<%= show(:title, item) %>
<% end %>
<% end %>
</h4>
<!-- fulltext -->
<% if show(:fulltext, item) && params["dem_discovery_search"]["is_fulltext_search"] == "1" %>
<div style="font-style: italic !important;font-family: 'Open Sans', sans-serif;font-size: 13px;"><%= show(:fulltext, item)%></div>
<% end %>
<!-- by creator -->
<% if item.stored(:contributor) != nil %>
<p><%= t(:by) %> <%= item.stored(:contributor).first %></p>
<% end %>
<% if item.stored(:description) != nil %>
<p><%= item.stored(:description).first %></p>
<% end %>
<!-- date -->
<!-- first coverage -->
<% if item.stored(:coverage) != nil %>
<p><%= show(:coverage, item)%> </p>
<% end %>
<span data-emerald-hook='discovery_item_details_extra'></span>
</div>
</div>
Sunspot Search printed
If I am searching by field title, query "prueba" THIS WORKS!
<Sunspot::Search:{:fq=>["type:Emerald\\:\\:Dem\\:\\:DigitalEntity"], :q=>"prueba", :fl=>"* score", :qf=>"title_texts contributor_texts creator_texts publisher_texts date_old_texts coverage_texts type_texts description_texts relation_texts subject_texts source_texts format_texts identifier_texts language_texts loan_texts rights_holder_texts rights_texts audience_texts provenance_texts instructional_method_texts accrual_method_texts accrual_periodicity_texts accrual_policy_texts parent_title_texts bibliotecaDipositaria_texts document_type_texts abstract_texts catalogue_url_texts text_date_texts temporal_texts titolPrincipal_texts isReplacedBy_texts replaces_texts fulltext_texts", :defType=>"edismax", :mm=>1, :bq=>["users_email_bookmark_sms:admin#greendata\\.com^2.0"], :hl=>"on", :"hl.simple.pre"=>"###hl###", :"hl.simple.post"=>"###endhl###", :"hl.fl"=>["title_texts", "description_texts", "fulltext_texts", "contributor_texts"], :start=>0, :rows=>30}>
If I am searching by field title, query "prueba" AND field description "descripcion" NOT WORKING!
<Sunspot::Search:{:fq=>["type:Emerald\\:\\:Dem\\:\\:DigitalEntity"], :q=>"(_query_:\"{!edismax qf='title_texts contributor_texts creator_texts publisher_texts date_old_texts coverage_texts type_texts description_texts relation_texts subject_texts source_texts format_texts identifier_texts language_texts loan_texts rights_holder_texts rights_texts audience_texts provenance_texts instructional_method_texts accrual_method_texts accrual_periodicity_texts accrual_policy_texts parent_title_texts bibliotecaDipositaria_texts document_type_texts abstract_texts catalogue_url_texts text_date_texts temporal_texts titolPrincipal_texts isReplacedBy_texts replaces_texts fulltext_texts' mm='1' bq='users_email_bookmark_sms:admin#greendata\\.com^2.0' hl='on' hl.simple.pre='###hl###' hl.simple.post='###endhl###' hl.fl='title_texts description_texts fulltext_texts contributor_texts'}prueba\" AND _query_:\"{!edismax qf='title_texts contributor_texts creator_texts publisher_texts date_old_texts coverage_texts type_texts description_texts relation_texts subject_texts source_texts format_texts identifier_texts language_texts loan_texts rights_holder_texts rights_texts audience_texts provenance_texts instructional_method_texts accrual_method_texts accrual_periodicity_texts accrual_policy_texts parent_title_texts bibliotecaDipositaria_texts document_type_texts abstract_texts catalogue_url_texts text_date_texts temporal_texts titolPrincipal_texts isReplacedBy_texts replaces_texts fulltext_texts' mm='1' bq='users_email_bookmark_sms:admin#greendata\\.com^2.0' hl='on' hl.simple.pre='###hl###' hl.simple.post='###endhl###' hl.fl='title_texts description_texts fulltext_texts contributor_texts'}descripcion\")", :fl=>"* score", :start=>0, :rows=>30}>
what am I doing wrong?
any suggestion would be welcome
if you need more parts of code do not hesitate to ask me
Thanks in advance!

Related

Rails5 what on earth is this assignment.errors showing me

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

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

rails does create twice when there is no record in a certain model unexpectedly

Guess
it's strange that it certainly occurs when there is no record in the database.
What I tried
I doubted that the cause was actually ajax so I all removed remote:true but it hardly worked.
controller
def create
#sell = current_user.orders.build(sell_params)
#buy = current_user.orders.build(buy_params)
if #sell.save
flash[:success] = 'your order has successfully submitted.'
notify_order(#sell.rate, #sell.amount, #sell.order_type)
#sell.rate.present? ? #sell.update(order_type: 'limit_sell') : #sell.update(order_type: 'market_sell')
fund = Fund.create_with(amount: 0, crypto_address_id: 1)
.find_or_create_by(user_id: current_user.id, kind: #sell.pair.split('_').last)
fund.update(in_use: #sell.rate * #sell.amount) if #sell.order_type == 'limit_sell'
# try to make orders done
market_checker(#sell.pair)
else
if Order.where(order_status: 'done', pair: params[:order][:pair]).present?
#currency_price = Sell.where(trading_status: 'done', currency_id: Currency.find_by_slug(params[:sell][:currency_id]).id)
#currency_price.present? ? #currency_price = #currency_price.last.price : #currency_price = ''
else
flash[:danger] = "Unfortunately, there is no trading right now so that we can't show you the chart"
end
#pair = params[:order][:pair].to_s
render :new
end
if #buy.save
flash[:success] = 'your order has successfully submitted.'
notify_order(#buy.rate, #buy.amount, #buy.order_type)
#buy.rate.present? ? #buy.update(order_type: 'limit_buy') : #buy.update(order_type: 'market_buy')
fund = Fund.create_with(amount: 0, crypto_address_id: 1).find_or_create_by(user_id: current_user.id, kind: #buy.pair.split('_').last)
fund.update(in_use: #buy.rate * #buy.amount) if #buy.order_type == 'limit_buy'
# try to make orders done
market_checker(#buy.pair)
else
if Order.where(order_status: 'done', pair: params[:order][:pair]).present?
#currency_price = Sell.where(trading_status: 'done', currency_id: Currency.find_by_slug(params[:sell][:currency_id]).id)
#currency_price.present? ? #currency_price = #currency_price.last.price : #currency_price = ''
else
flash[:danger] = "Unfortunately, there is no trading right now so that we can't show you the chart"
end
#pair = params[:order][:pair].to_s
render :new
end
end
model
class Order < ApplicationRecord
belongs_to :user
validate :deposited_btc_enough?
validate :insufficient?
validates :amount, format: { with: /\A\d+(?:\.\d{0,8})?\z/ }, numericality: { greater_than: 0.000000009, less_than: 100_000_000 }, presence: true
validate :rate_check
validates :rate, format: { with: /\A\d+(?:\.\d{0,8})?\z/ }, numericality: { greater_than: 0.000000009, less_than: 100_000_000 }, if: :rate_present?
validate :checking_order_type
def rate_present?
rate.present?
end
def checking_order_type
if order_type == 'sell_limit' || order_type == 'buy_limit'
errors.add(:Please, 'specify the rate of your order.') unless rate.present?
end
if order_type == 'sell_market' || order_type == 'buy_market'
errors.add(:You, "can't specify the rate of your order.") if rate.present?
end
end
def deposited_btc_enough?
if rate.present?
if rate.to_d > '0'.to_d && amount > 0
deposited_amount = user.fund.amount if user.fund.amount.present?
amount = rate.to_d * amount.to_s.to_d
if deposited_amount.present?
if coin_to_satoshi(amount).to_i > coin_to_satoshi(deposited_amount).to_i
errors.add(:Your, 'deposited yen is short to order.')
end
else
errors.add(:You, "haven't deposited yen yet or Your transaction hasn't confirmed yet.")
end
else
errors.add(:You, "can't specify negative numbers here.")
end
end
end
def to_param
uuid
end
def insufficient?
if amount.present? && order_type.split('_').last == 'sell'
if CurrencyUser.find_by(user_id: user.id, currency_id: Pair.find_by(name: pair).currency_id).amount < amount
errors.add(:amount, 'of this order is more than your holdings.')
errors[:base] << 'Errors that are related to this order exist.'
end
end
end
def is_number?(string)
true if Float(string)
rescue StandardError
false
end
def rate_check
if rate.present?
errors.add(:You, 'can only specify numbers') unless is_number?(rate)
errors.add(:You, "can't specify the rate as a negative number.") unless '0'.to_d < rate.to_d
end
end
end
form
<%= form_for(#sell,remote:true) do |f| %>
<% if #sell.errors.any? %>
<div id="error_explanation" class="alert alert-danger">
<h2><%= #sell.errors.count %>error(s) exist(s).</h2>
<ul>
<% #sell.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :pair,value:#pair%>
<%= f.hidden_field :order_type,value:"market_sell"%>
<p>amount whatever you want to sell like 100</p>
<div class="input-group">
<%= f.number_field :amount, class: 'form-control form-group',placeholder:"amount"%>
</div>
<%= f.submit 'done', class: "btn btn-large bg-info" %>
<% end %><br>
<%= form_for(#buy,remote:true)do |f| %>
<% if #buy.errors.any? %>
<div id="error_explanation" class="alert alert-danger">
<h2><%= #buy.errors.count %>error(s) exist(s).</h2>
<ul>
<% #buy.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Thanks
Your create method has way too much complexity and I'm assuming you have not written this method with test driven development because you would have broken it down into smaller methods if you had, likely moving more of the logic to the model. I also hope this is not how your code style looks in real life. At first glance, I'm assuming your problem is this:
def create
# why are you creating 2 orders?? Can you change this:
#sell=current_user.orders.build(sell_params)
#buy=current_user.orders.build(buy_params)
#to something more like:
#order = order_from_params
#...omitting rest of this code because it needs a lot of refactoring.
end
private
def order_from_params
#you should probably only deal with 1 order at a time either buy or sell
# you must have a field in orders table to indicate buy or sell, probably int?
if sell_params.present?
#order = current_user.orders.build(sell_params)
else
#order = current_user.orders.build(buy_params)
end
end
Then you'll need to simplify the logic in create method since you only have one model to deal with. You should NOT rely on nor do 2 if #order.save inside the create action since you should again only be creating 1 order at a time. This should get you headed in the right direction. And if you're not doing test driven development, you're gonna have a lot worse problems then what you have already.

How find users in database with same content in Ruby on Rails?

In my database I have column :inviter and some users have same content in that column
I want find all them,with same content
In my user controller:
def foll
#user = current_user
#ref = User.find_by_invite(#user.id.to_s)
if !#ref || !#ref.pay_s || !#ref.pay_1 || !#ref.pay_2 || !#ref.pay_3
#referals = false
else
#referals = User.find_by_invite(#user.id.to_s)
end
end
In my views
<% if #referals != false %>
<% #referals.each do |user| %>
<h4>
<%= link_to user.name, user %> status : Good
</h4>
<% end %>
<% else %>
<h3>You dont have any referrals</h3>
<% end %>
When I try I have this error
undefined method `each' for #<User:0x007f13e41b0068>
this will raise error since
#referals = User.find_by_invite(#user.id.to_s)
will return single record
you can try #where to query all referrals
#referals = User.where(invite: #user.id.to_s)
you can also refer here for other queries
http://guides.rubyonrails.org/active_record_querying.html
hope this helps
Hope this help:
controller:
def foll
#user = current_user
#ref = User.find_by_invite(#user.id.to_s)
if !#ref || !#ref.pay_s || !#ref.pay_1 || !#ref.pay_2 || !#ref.pay_3
#referals = []
else
#referals = User.where(invite: #user.id.to_s)
end
end
view:
<% if #referals.any? %>
<% #referals.each do |user| %>
<h4>
<%= link_to user.name, user %> status : Good
</h4>
<% end %>
<% else %>
<h3>You dont have any referrals</h3>
<% end %>

Creating a method that could allow me to change my user's post content in Ruby

So im creating a website, and on that website people can post links. Depending on what the link is, the post will render differently. For example, a post with a link to youtube.com/somevideo will render an embeded video. A link ending in JPG will display that image.
I have written the following in my view
<% link_type = extract_content_from_url(post.link) %>
<div class ="preview_of_post">
<% if post.link %>
<% if link_type == "youtube" %>
<%= youtube_embed(post.link) %>
<% end %>
<br />
<%= link_to (post.link), (post.link) %>
<% end %>
And in my helper, I have this:
module PostsHelper
def extract_content_from_url(url)
if url != ""
unless url.include?("http://")
post.link = "http://#{post.link.downcase}"
end
else
return "nil"
end
if url.include? == "youtube.com/watch" #youtube link
return "youtube"
end
if File.extname(url) == ".gif" || File.extname(url) == ".jpg" ||
File.extname(url) == ".png" || File.extname(url) == ".jpeg"
return"picture"
end
end
def youtube_embed(youtube_url)
if youtube_url[/youtu\.be\/([^\?]*)/]
youtube_id = $1
else
youtube_url[/^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/]
youtube_id = $5
end
render(:inline=> "<iframe title='YouTube video player' width='640' height='390' src='http://www.youtube.com/embed/#{ youtube_id }' frameborder='0' allowfullscreen></iframe>")
end
end
When running my code, I get the following error:
Any suggestions?
Thanks.
url.include? == "youtube.com/watch" is not valid. include? is a method which takes an argument. You probably mean url.include? "youtube.com/watch".

Resources