autocomplete field is empty when editing form - ruby-on-rails-4

I have a sample model in which belongs_to a patient model.Using rails-jquery-autocomplete I have managed to implement an autocomplete field where one can search patient's code and it works well. However when editing the form, the patient code is empty on the form.
How should I fix it?
App/views/sample/_form.html.erb
<div class="field">
<%= f.label :patient_code %><br>
<%= f.hidden_field :patient_id, id: 'patient_id' %>
<%= f.autocomplete_field :patient_code, autocomplete_patient_code_samples_path, id_element: '#patient_id' %>
</div>

I faced the same issue while editing the saved model, a quick workaround would be as follows:
...
<%= f.autocomplete_field :patient_code, autocomplete_patient_code_samples_path, id_element: '#patient_id', value: (!#sample.new_record?)? #sample.patient.code : '' %>
...
Assuming that the instance variable is #sample. Modify it according to your scenario. Cheers!

Related

Ruby on Rails, Datepicker search between two dates

I am a new ROR user trying to implement a DateTime picker to select dates for a search function.
My problem is that when I enter two dates (date from, and date to) in the DatePicker, I get inconsistent results from the search. Sometimes I get no results, and sometimes I get all the results. I am also using the bootstrap-datepicker-rails gem as well as the ransack gem.
This is what my view looks like
<div class="field">
<%= f.label :departure_date_gteq, "Departure Date Between" %>
<%= f.search_field :departure_date_gteq, "data-provide" => "datepicker" %>
<%= f.label :return_date_lteq, "and" %>
<%= f.search_field :return_date_lteq, "data-provide" => "datepicker" %>
</div>
The two database columns I am referencing are departure_date, and return_date. The date stored is datetime and looks like this,
departure_date
2016-08-07 00:00:00.000000
return_date
2016-08-14 00:00:00.000000
I enter 2016-08-06 and 2016-08-15 in the DatePickers and I am returned all the results.
Could my search form DatePicker be sending data that cannot be correctly compared to the DateTime in the database?
Am I using the 'gteq' and 'lteq' calls correctly?
EDIT #1
#Michael Gaskill, you are correct that the problem is the date formatting. When I enter a date manually, I get the correct search results. I just need to figure out how to correct the formatting before its passed to the controller.
Here is what my controller looks like.
class HomeController < ApplicationController
def index
#search = Sailing.search(params[:q])
#sailings = #search.result
... Other calls ...
end
end
Here is the full piece of code in my view that generates sailings content. Note that I'm using search_for_for which is part of the ransack gem.
<%= search_form_for #search, url: root_path, method: :post do |f| %>
<div class="field">
<%= f.label :cruise_ship_name_or_cruise_ship_company_or_destination_identifier_cont, "Cruise Ship Name" %>
<%= f.text_field :cruise_ship_name_or_cruise_ship_company_or_destination_identifier_cont %>
</div>
<div class="field">
<%= f.label :departure_date_gteq, "Departure Date Between" %>
<%= f.search_field :departure_date_gteq, "data-provide" => "datepicker" %>
<%= f.label :return_date_lteq, "and" %>
<%= f.search_field :return_date_lteq, "data-provide" => "datepicker" %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
Thanks.
You need to convert the string-formatted dates entered in the form (either via the DatePicker or manually-entered) to Date or DateTime values. When you query the database, use this DateTime#strptime to convert:
MyTable.where(date_field_to_search: DateTime.strptime(date_value_from_ui, "%F %T")
You can check out the formats available as the second argument to strptime, using the instructions at DateTime:strftime. Note that strftime and strptime are used to convert back and forth between DateTime and formatted String values.
In your Sailing#search(params[:q]) example, you can either implement the solution in Sailing#search (if you have access to change that code) or prior to calling Sailing.search.
Here is how you might implement this in Sailing#search:
class Sailing
def search(args)
datetime = args[:date_field_to_search]
if datetime.kind_of?(String)
datetime = DateTime.strptime(datetime, "%F %T")
end
# other search functionality
end
end
or, prior to calling Sailing#search:
datetime = params[:q][:date_field_to_search]
if datetime.kind_of?(String)
datetime = DateTime.strptime(datetime, "%F %T")
end
Sailing.search(params[:q].merge({ date_field_to_search: datetime })

rails4-autocomplete with belongs to association

I want to implement autocomplete via rails4-autocomplete
Rails 4.2.4
Here is the controller
app/controllers/samples_controller.rb
class SamplesController < ApplicationController
autocomplete :patient, :code
Here is the route file,
config/routes.rb
resources :samples do
get :autocomplete_patient_code, on: :collection
end
And that's the view
app/views/samples/_form.html.erb
<div class="field">
<%= f.label :patient_code %><br>
<%= f.autocomplete_field :patient_id, autocomplete_patient_code_samples_path %>
</div>
With this code I mange to get the autocomplete
However I get invalid foregin key error when try to save the sample that's because the patient's code is passed to the foregin key instead of ID. How do I fix this?
Here is the request Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"blabla",
"sample"=>{"patient_id"=>"A123",
"commit"=>"Create Sample"}
Get "/samples/autocomplete_patient_code?term=A12" returns
{"id":"15","label":"A123","value":"A123"}]
After reading the GitHub documentation of rails4-autocomplete, I devised the following solution:
Add attr_accessor :patient_name to your Sample model and modify the form as follows:
...
<%= f.autocomplete_field :patient_name, autocomplete_patient_code_samples_path, id_element: '#patient_id' %>
<%= f.hidden_field :patient_id, id: 'patient_id' %>
...
With this change whenever you select any patient name, that patient's ID will be updated on the hidden field and it will be submitted as patient_id.
Hope this solves your problem.
Source: Github

Rails: Conditional nested attributes in edit form

I have a model called Offer and another called PurchasinGroup
Offer has many PurchasingGroups
Offer accepts nested attributes for PurchasingGroups
While creating an offer you can add as many PurchasingGroups as you want.
PurchasingGroup has a boolean attribute called active.
while editing an Offer you can see all the created PurchasingGroups, however I want to let the user edit only the PurchasingGroups that are active, and do not display the inactive purchasing groups.
This is my edit action in offers_controller.rb:
def edit
#offer = Offer.find(params[:id])
end
And this is my form (only the part that matters):
<fieldset>
<legend>Purchasing groups</legend>
<%= f.fields_for :purchasing_groups do |builder| %>
<%= render partial: 'purchasing_group_fields', locals: { f: builder } %>
<% end %>
</fieldset>
In the edit form all the purchasing groups are being shown for edit, I want to show only those that are active I mean purchasing_group.active == true
How is the best way to do it?
<%= f.fields_for :purchasing_groups, #offer.purchasing_groups.where(active: true) do |builder| %>
<%= render partial: 'purchasing_group_fields', locals: { f: builder } %>
<% end %>
on the other hand, you can also add a association in your model
class Offer
has_many :active_purchasing_groups, class_name: "PurchasinGroup", -> { where(active:true) }
...
end
and then
<%= f.fields_for :active_purchasing_groups do |builder| %>
<%= render partial: 'purchasing_group_fields', locals: { f: builder } %>
<% end %>

RoR: How to set the value in a collection_select from the database in the edit view (1:many relation)

I am at the moment creating a complicated rails form for 1:n relationship with nested form and collection select with values from yet another data table.
So far, it overwrites the database value with the first entry in the values list of the collection_select whenever the user does not select the correct value before update. I still need to set the initial value in the collection_select correctly.
I have read a lot of questions on SO already, most relevant was:
f-collection-select-not-displaying-the-selected-value
The only thing still missing (I hope!), is the setting of the value of the form field from the database, so it does not get overwritten with a default value from the selects selectable values, even though the user has not touched the select.
This snippet is derived from my code and the solution to the abovementioned question and is wrong.
Let a person have many things and validthings contains the possible values for things:
In the things table there will only be Thing strings, that are also in the validthings table. It is possible to give the collection_select selected param a string from the things table that can be identified in the list of values from the validthings table.
<div class="col-md-12">
<%= form_for(#person) do |f| %>
<%= f.fields_for :things do |d| %>
<%= d.hidden_field :id %><%= d.hidden_field :person_id %>
<%= d.collection_select(:Thing, Validthings.all, :Thing, :Thing, {:selected => #person.things.map(&:id).Thing.to_s} ) %>
<% end %>
<% end %>
</div>
This is what is wrong:
#person.things.map(&:id).Thing.to_s
And yes, in tables persons and things and validthings the column is named "Thing". It is a unique string in table validthings - the database structure was not my idea, I only work with it.
Found a helpful answer here: rails-accessing-current-value-of-a-symbol
to another subject, but my problem was that I did not know how to access the information that I knew must already be loaded.
This is how I can specify the default value of a collection_select to be the data from the database:
<div class="col-md-12">
<%= form_for(#person) do |f| %>
<%= f.fields_for :things do |d| %>
<%= d.hidden_field :id %><%= d.hidden_field :person_id %>
<%= d.collection_select(:Thing, Validthings.all, :Thing, :Thing, {:selected => d.object.Thing} ) %>
<% end %>
<% end %>
</div>
where d.object.Thing is the value of the respective object of the form element for the attribute "Thing", which is already present in the form.
I'd be very grateful for constructive ideas, in case my approach is un-ruby-like or some such. I am rather new to ruby, rails etc.

Indicate that an uploaded file is present in edit form -- paperclip

In my current solution, I am able to put a checkbox in the edit form so that users can delete attachment. However, there is no indication for the user that a file has been uploaded, the name of that file, etc. so that he can decide whether to delete.
Right now the form look like this. The first material is an existing one, the next 3 are due to
def edit
#post = Post.find(params[:id])
3.times { #post.post_materials.new }
end
As you can see, it's very hard to distinguish between them. Ideally, I want the first material file name to appear somehow.
<%= form_for #post, :html => { :multipart => true } do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
Materials:
<ul>
<%= f.fields_for :materials, :html => { :multipart => true } do |materials_form| %>
<li>
<%= materials_form.label :asset %>
<%= materials_form.file_field :asset %>
<%= materials_form.label :_destroy, class: "checkbox inline" do %>
Remove attachment <%= materials_form.check_box :_destroy %>
<% end %>
</li>
<% end %>
</ul>
<%= f.submit "Submit", class: "btn btn-large" %>
<% end %>
Running paperclip's generator creates a migration to add 4 attributes on your model, as you can see here. These attributes are:
<attachment>_file_name
<attachment>_file_size
<attachment>_content_type
<attachment>_updated_at
So, If you ran the generator this way: rails generate paperclip post_material asset, on your PostMaterial model, you will have these attributes:
asset_file_name
asset_file_size
asset_content_type
asset_updated_at
Then, on your code you can do something like this:
if materials_form.object.asset.exists? #object represents the current post_material instance
#show a label with object.asset_file_name
else
#render materials_form.file_field :asset
end