I am getting my heads around many things RoR - by developing a small movie database that has actors and movies.
I successfully setup Ransack to do two things for me:
Following Chris' great tutorial on autocomplete https://gorails.com/episodes/global-autocomplete-search I now have a working search field in my navbar with dropdown, autoselect etc - all works like charm :)
Set up a separate "moviesearch" method in my mainpage controller - with corresponding form etc - working great too.
Code of moviesearch method:
#q = Movie.ransack(params[:q]
#movies_search = #q.result(distinct: true).includes(:genres, :actors)
However I now try to setup an "actorsearch" method - also in my mainpage controller - with corresponding form etc... doesn't work. It does reply the right index page (view/actors/index.html.erb), but it doesn't pass any of the search parameters on.
Code of actorsearch method:
#q = Actor.ransack(params[:q])
#actors_search = #q.result(distinct: true).includes(:movies, :actor_attributes)
When I check the console - the moviesearch method triggers something like this:
SELECT COUNT(*) FROM (SELECT DISTINCT `movies`.* FROM `movies` WHERE `movies`.`title` LIKE '%lord%' ORDER BY `movies`.`sort_title` ASC) subquery_for_count
But the actorsearch triggers only:
SELECT COUNT(*) FROM `actors`
Not sure what's wrong...
Update: Here's the form code for the actor search - omitted all html-only stuff (div's etc)
<%= search_form_for #q do |f| %>
<%= f.label :display_name_cont, 'Name contains', class: 'form-label mb-0' %>
<%= f.search_field :display_name_cont, class: 'form-control' %>
<%= f.label :gender_eq, 'Gender is', class: 'form-label mb-0' %><%= f.search_field :gender_eq, class: 'form-control' %>
<%= f.label :actor_attributes_id_in, 'Attributes', class: 'form-label mb-0' %>
<%= f.collection_select(:actor_attributes_id_in, ActorAttribute.order(:name), :id, :name, {}, { class: 'form-select bootstrap', id: 'attribute-select', multiple: true } ) %>
<%= f.label :born_gteq, 'Born between', class: 'form-label mb-0' %><%= f.number_field :born_gteq, class: 'form-control' %></div>
<%= f.label :born_lteq, 'and', class: 'form-label mb-0' %>
<%= f.number_field :born_lteq, class: 'form-control' %>
<%= f.label :rating_gteq, 'Actor rated at least', class: 'form-label mb-0' %>
<%= f.number_field :rating_gteq, class: 'form-control' %>
<%= f.label :movies_id_eq, 'Movies starring in', class: 'form-label mb-0' %>
<%= f.collection_select(:movies_id_in, Movie.order(:sort_title), :id, :title, {}, { class: 'form-select bootstrap', id: 'movie-select', multiple: true } ) %>
<%= f.submit class: 'btn btn-outline-primary' %>
<% end %>
And I didn't quite know what you mean with "puts params[:q] into the controller. I have already tried to check the params with outputting debug(params[:q]) in various places - for example, in my actors index page, it shows like this:
parameters: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
display_name_cont: john
gender_eq: ''
actor_attributes_id_in:
- ''
born_gteq: ''
born_lteq: ''
rating_gteq: ''
movies_id_in:
- ''
permitted: false
...which looks pretty similar to the output for movies... at least I couldn't spot any immediate issue here?
Related
I have this models where I wanna update my typestored columns using update_columns active record
I have searched numerous answers in stack, doesn't seems to have lot of resources regarding typestored.
show.html.erb
<%= form_tag print_booking_path(#booking), method: 'post' do %>
<%= label_tag :name %>
<%= text_field_tag :name, '', class: 'form-control' %>
<%= label_tag :age %>
<%= text_field_tag :age, '', class: 'form-control' %>
<%= submit_tag "Print", class: "btn btn-default" %>
<%= link_to 'Cancel', '#', class: 'btn btn-default', data: { dismiss: 'modal' } %>
<% end %>
bookings_controller
def print
#booking = Booking.find(params[:id])
if #booking.print_model(current_user, params[:name], params[:age])
render :print
else
render :print
end
end
booking model
def print_model(user, name_test, age_test)
self.update_columns(name: name_test, age: age_test)
end
typestore under booking model
typed_store :profile, coder: PostgresCoder do |i|
i.string :name, default: ""
i.integer :age, default: 0
end
the error appeared to be like this
can't write unknown attribute name
it's same like if I wanna to update like this self.increment!(:age)
I made a few tests here, and I don't know if it makes sense, but in case of updating stores, all the typestored columns are inside just one real column in the database (that are a normally in hash or Json).
So the straight foward way to do it is to wrap in brackets.
Try changing:
self.update_columns( name: name_test, age: age_test )
To:
self.update_columns( profile: { name: name_test, age: age_test} )
I'm trying to set a site-wide global variable in my Rails application using the form at the following site:
http://spin360-staging.herokuapp.com/printer
The results should be visible here:
http://spin360-staging.herokuapp.com/printer.json
However, if you refresh the json, you'll see that it doesn't seem persistent - it seems to change values when you refresh the page.
Here's what the form looks like:
<%= form_tag edit_printer_path do %>
<%= label_tag "Type" %>
<%= select_tag(:type, options_for_select(
[
['Set', "set"],
['Spin', "spin"]
], 1
)) %>
<%= label_tag "ID" %>
<%= text_field_tag :print_id %>
<%= label_tag "Format" %>
<%= select_tag(:layout, options_for_select(
[
['Receipt', "receipt"],
['Filmstrip', "filmstrip"],
['Flipbook', "flipbook"]
], 1
)) %>
<%= submit_tag "Submit", :class => "submit_button" %>
And the controller method:
def edit_printer
Rails.application.config.print_type = params[:type]
Rails.application.config.print_id = params[:print_id]
Rails.application.config.print_layout = params[:layout]
redirect_to(:back)
end
And finally, the JSON template (printer.json.erb)
{
"print": [{"type":"<%= Rails.application.config.print_type %>","id":<%= Rails.application.config.print_id %>,"layout": "<%= Rails.application.config.print_layout %>"}]
}
I have a field called delivery_day which is of type string in delivery_preference model.
In form, I want to provide 7 checkboxes for each day like Sunday,Monday,etc., and later want to concat.
For example if a user checks Sunday and Friday, I want to concat & store it as "Sunday,Friday" in delivery_day field.
Thanks in Advance!!
You can design your form like this -
<%= form_for #delivery_preference do |f|%>
<%= f.check_box :delivery_day, {multiple: true}, "Sunday" %>Sunday
<%= f.check_box :delivery_day, {multiple: true}, "Monday" %> Monday
<%= f.submit "Add" %>
<% end %>
After submitting the form, you can get your check box selections in your controller as follows:
def your_action_name
params[:delivery_preference][:delivery_day].delete("0")
DeliveryPreference.create(delivery_day: params[:delivery_preference][:delivery_day].join(","))
end
Hope it helps!
Might have better solutions, but when I encountered similar problem, I used check_box_tag to solve it.
<%= check_box_tag "delivery_preference[delivery_day][0]", 'monday' %>Monday
<%= check_box_tag "delivery_preference[delivery_day][1]", 'tuesday' %>Tuesday
<%= check_box_tag "delivery_preference[delivery_day][2]", 'wednesday' %>Wednesday
<%= check_box_tag "delivery_preference[delivery_day][3]", 'thursday' %>Thursday
<%= check_box_tag "delivery_preference[delivery_day][4]", 'friday' %>Friday
<%= check_box_tag "delivery_preference[delivery_day][5]", 'saturday' %>Saturday
<%= check_box_tag "delivery_preference[delivery_day][6]", 'sunday' %>Sunday
then you will receive an array like { deliver_day: ['monday', 'tuesday'] } in you controller. You can choose to concat in your controller, and then save, or you can move the logic to your model.
in your controller, you strong parameter should be like
params.require(:delivery_preference).permit(.., :deliver_day => [])
to permit the array.
I do not have enough reputation to leave a brief comment yet. However, does your migration have delivery_day have something similar to t.boolean :public, default: true_or_false_here within it?
If so, within the form, you could have something like:
...
<div class="form-group">
<%= f.label :public, class: 'checkbox' do %>
<%= f.check_box :public %> Monday
<% end %>
</div>
<div class="form-group">
<%= f.label :public, class: 'checkbox' do %>
<%= f.check_box :public %> Tuesday
<% end %>
</div>
...
After above, you could designate (via boolean logic) your "concat & store it as "Sunday,Friday"
I am very new to rails and try to make an advance search form which takes two values 'blood_group' and 'area' and based upon that search the records from the database are fetched and will display on the same page (find.html.erb)
I have tried something in find.html.erb but there is an error occurred 'undefined method [] for nil:Nil class' where my search form exists. please help to get out of this error.
Here is my search form in find.html.erb
<%= form_tag find_path , method: :get do %>
<p> <%= label_tag :blood_group %><br />
<%= select_tag (:blood_group), options_for_select(%w[ A+ B+ O+ AB+ A- B- O- AB-]), params[:blood_group] %> </p>
<p> <%= label_tag :area %><br />
<%= select_tag (:area), options_for_select(%w[Indore Vijay_Nagar Bhawar_Kuwa Rajendra_Nagar Geeta_Bhawan Aerodram Tejaji_Nagar Raj_Mohalla Rajwada Chandan_Nagar Gandhi_Nagar Arvindo MY Bombay_Hospital]) , params[:area] %> </p>
<%= submit_tag "Search" , class: "btn btn-primary" , name: nil %>
<% end %>
The error is at the lines where I used select tag.
below is my find action in Donor controller
def find
#donors = Donor.search(params[:blood_group], params[:area]).all
end
And Donor.rb is as follows
class Donor < ActiveRecord::Base
def self.search(blood_group, area)
return all unless blood_group.present? || area.present?
where(['blood_group LIKE ? AND area LIKE ?', "%#{blood_group}%", "%#{area}%"])
end
end
Your search form must be like this:
<%= form_tag find_path , method: :get, remote: true do %>
<p> <%= label_tag :blood_group %><br />
<%= select_tag (:blood_group), options_for_select(%w[ A+ B+ O+ AB+ A- B- O- AB-]) %> </p>
<p> <%= label_tag :area %><br />
<%= select_tag (:area), options_for_select(%w[Indore Vijay_Nagar Bhawar_Kuwa Rajendra_Nagar Geeta_Bhawan Aerodram Tejaji_Nagar Raj_Mohalla Rajwada Chandan_Nagar Gandhi_Nagar Arvindo MY Bombay_Hospital]) %> </p>
<%= submit_tag "Search" , class: "btn btn-primary" , name: nil %>
<% end %>
Modify your controller as:
def find
#donors = Donor.search(params[:blood_group], params[:area]).all
respond_to do |format|
format.js
end
end
Then add find.js.erb to show the searched content.
I am trying to implement a dropdown menu to display all the names I have in my database. I tried unsuccessfully the following code:
<%= form_for #airline, remote: true do |f| %>
<%= f.select :name, [#airlines.names] %>
<%= f.submit %>
<% end %>
Controller:
def index
#airlines = Airline.all
#airline = Airline.new
end
I assume the solution is quite straight forward but I couldn't find it.
This should do
<%= f.select(:name, #airlines.collect { |airline| [airline.name,airline.id] }, {:include_blank => 'Choose 1'},:class=>"class_name") %>