Ruby how to get array with boolean? - ruby-on-rails

i would like to get a arrau of boats, but i would like that just show the boats with rent boolean set to true.
how can acomplish this?
i've added:
#boats = Boat.where(rent: true)
But did not worked
i even tried the method model
def rents
self.class.where(rent: true)
end
and did not worked either

You can do something like this
<% #boats.where(:rent=>true).each do |t| %>
<%= t.name %>
<%end%>
<%= #boats.where(:rent=>true).all %>
or
<% if boats.where(:rent=>true).exists? %>
<%= t.name %>
<%end%>
or
def rents
#boats.where(:rent=>true).all
end

Related

Ruby on Rails: Why empty value is displayed when form for creation of new objects in DB is included?

I am newbie. I am trying to develop a simple web application involving shops and candies where a shop can have many candies.
I have the following code in my shops/show.html.erb which displays list of candies twice.
<% i=0 %>
<% for candy in #shop.candies do %>
<% i+=1 %>
<%= i %> <%= candy.name %>
<% end %>
<%= form_for([#shop, #shop.candies.build]) do |f| %>
<%= render(:partial => 'form',
:locals => {:f => f, :header => "Add a Candy",
:placeholder => "Enter a candy name"}) %>
<% end %>
<% i=0 %>
<% for candy in #shop.candies do %>
<% i+=1 %>
<%= i %> <%= candy.name %>
<% end %>
My code in _form.html.erb for creating a new candy:
<%= f.text_field(:name, :placeholder=> placeholder, :class=>"form-control custom-input")%>
<%= button_tag( :class => "btn btn-primary mb-2 btn-custom btn-custom-sc") do %>
<i class="fas fa-plus icon"></i>
<% end %>
Code of Shops Controller:
class ShopsController < ApplicationController
def show
#shop = Shop.find(params[:id])
#unshelved_candies = #shop.candies.unshelved_candies
end
private
def shop_params
params.require(:shop).permit(:name)
end
end
Code of Candies Controller:
class CandiesController < ApplicationController
def create
#shop = Shop.find(params[:shop_id])
#candy = #shop.candies.create(candy_params)
redirect_to(shop_path(#shop))
end
private
def candy_params
params.require(:candy).permit(:name)
end
end
end
When I run the code and view it on browser, I notice that it creates an empty candy in the second loop (not in database). However, when I remove the form for creating candies, it behaves as it should. I am unable to understand why it's looping one more time and displaying blank value.
The output of the first loop is the correct one:
Candy 1
Candy 2
Candy 3
And the output of second loop is:
Candy 1
Candy 2
Candy 3
[<---Empty. I am not inserting anything new to the database]
Can anybody tell me why it is displaying a blank value in second loop and how to prevent this extra iteration?
I believe the "extra" candy is the one you're instantiating here:
<%= form_for([#shop, #shop.candies.build]) do |f| %>
The candy name for the new candy is nil, so you're getting the blank.
BTW, this:
<% i=0 %>
<% for candy in #shop.candies do %>
<% i+=1 %>
<%= i %> <%= candy.name %>
<% end %>
Strikes me as non-idiomatic ruby. I would expect to see something more like:
<% #shop.candies.each.with_index(1) do |candy, index| %>
<%= index %> <%= candy.name %>
<% end %>
I guess a brute force way of making sure you don't get that extra candy would be to do something like:
<% #shop.candies.each.with_index(1) do |candy, index| %>
<% unless candy.new_record? %>
<%= index %> <%= candy.name %>
<% end %>
<% end %>
You might also try:
<%= form_for([#shop, #candy]) do |f| %>
Which I believe can be written:
<%= form_for(#shop, #candy) do |f| %>
If you want to save yourself a couple of key strokes (they add up over time).
And then in your ShopsController do:
class ShopsController < ApplicationController
def show
#shop = Shop.find(params[:id])
#candy = Candy.new
#unshelved_candies = #shop.candies.unshelved_candies
end
private
def shop_params
params.require(:shop).permit(:name)
end
end
This is also nice because it avoids:
#shop.candies.build
Which requires that your view knows a lot about the relationship between shop and candies and also requires that your view interacts directly with the database.
Since you're apparently using nested routes, you might want to look at the shallow: true directive.
Also (this is not related to your question), you might want to be thoughtful about the Law of Demeter. I notice you do:
#unshelved_candies = #shop.candies.unshelved_candies
Personally, I would do something more like:
#unshelved_candies = #shop.unshelved_candies
And in Shop, you might have something like:
class Shop < ApplicationRecord
def unselved_candies
candies.unshelved
end
end
And in Candy, something like:
class Candy < ApplicationRecord
class < self
def unshelved
where(shelved: false) # or however you determine a candy is unshelved
end
end
end
Many people would make unshelved a scope, which is another way of doing the same thing.
This way, your ShopsController knows less about the mechanics of the relationships between shops and candies and shelved status. FWIW.

Display title instead of id from search results

I have spent hours on this single problem, I am desperate for help.
The below html displays the correct car name and the car.manufacture_id displays the correct manufacture id, except I need to display manufacture.name and can not figure out how to do that. How do I display car.manufacture.name?
search.html.erb
<% #cars.each do |car| %>
<%= car.manufacture_id %>
<%= link_to car.name, manufacture_path(car.manufacture_id) %>
<% end %>
search_controller.rb
def search
if params[:q].nil?
#cars = []
#manufactures = []
else
#cars = Car.search params[:q]
#manufactures = Manufacture.search params[:q]
end
end
What do your car and manufacture models looks like, can you show the code for them? The schemas would help too. If your models are setup right car.manufacture.name should have worked.
If you do
<% #manufactures.each do |manufacture| %>
<%= manufacture.id %>
<%= manufacture.name %>
<% end %>
Does this work?
Also this might work, if the manufacturers are being found by Manufacture.search params[:q]
<%= #manufactures.find(car.manufacture_id).name %>
or if they are not
<%= Manufacture.find(car.manufacture_id).name %>

If two DateTime stamps are the same in Rails

I have created a simple appointment system, and I now need to display something inside a loop if there's two or more appointments with the same date and time. The appointments are displayed in order of time, so they're just appearing one after the other.
Controller
def index
#todays_apps = current_user.appointments.order(time ASC)
end
View
<% #todays_apps.each do |app| %>
<%= app.business_name %>
<%= app.business_address %>
<%= app.time %>
<% end %>
I'm looking to display a message or icon the appointment shares a date and time with another appointment. Tried a collection of things with no luck.
You can group your collection by time and modify your iteration accordingly. You can group it like
#todays_apps.group_by(&:time)
The outcome will be something like
=> { timestamp1 => [app1,app2], timestamp2 => [app3], timestamp3 => [app4]}
Or you can try a quick hacky way like:
<% previous_time = nil %>
<% #todays_apps.each do |app| %>
<%= app.business_name %>
<%= app.business_address %>
<%= 'Your message or class or anything' if previous_time == app.time %>
<%= previous_time = app.time %>
<% end %>
Try Like this:
controller:
def index
#appointments = current_user.appointments.order("time ASC")
#todays_apps = #appointments.group_by(&:time)
end
View:
<% #todays_apps.each do |time, appointments| %>
<%= time %>
<% appointments.each do |appointment| %>
<%= appointment.business_name %>
<%= appointment.business_address %>
<% end %>
<% end %>
It will list all the appointments for particular time.
Thanks

Rails Form element to convey two values

I have a form that takes bookings for an event for people. The form displays events vertically, and a name & checkbox for each of the possible people next to each event.
How should I best convey the two pieces of information that i need per checkbox? that is, the event_id and the person_id
I'm not totally sure wether I got you right. This is the model I assume you're talking about:
# event.rb
class Event
has_many :people
scope :possible_people, -> { #whatever .. }
end
# person.rb
class Person
belongs_to :event
end
# events_controller.rb
class EventsController
def index
#events = Event.all
end
end
And this might be a possible solution to change an events relation to people:
# index.html.erb
<ul id="events">
<% #events.each do |event| %>
<li class="event">
<%= form_for #event do |form| %>
<% event.possible_people.each do |person| %>
<%= check_box_tag "event[person_ids][]", person.id, #event.people.include?(person) %>
<% end %>
<%= f.submit_tag 'Save Event' %>
<% end %>
</li>
<% end %>
</ul>
The important part is <%= check_box_tag "event[person_ids][]", person.id, #event.people.include?(person) %> where you actually change the the relation of a specific person to the event.
Good luck ;)
Well, you can try out something like below line, I am assuming you have a multiselect checkboxes and i am passing a Hash of event_id => plate_id as value to checkbox.
<%= check_box_tag 'booking[event_people_ids][]', {booking.event_id => booking.plate_id} %>
You will get the value in params as:
booking => {event_people_ids =>["{"72"=>"3"}}
I ended up doing this:
<%= check_box_tag "booking[]", "#{event.id}-#{person.id}" %>
and then in then to process them:
params[:booking].each do |booking|
booking = booking.split('-')
a = {
:booking_id => #booking.id,
:person_id => booking[1],
:event_id => booking[0]
}
Appointment.create(a)
end
I was hoping for a more railish way to do it but this works.

Scope Search Field

I have a scope configured to search a database on a name. The scope looks like:
class AdminVerified
scope :search, lambda {|query| where(["name LIKE ?", "%#{query}%"])}
end
I want to call this scope in a form. Does anyone know how to call a scope in a form. I want to create a form_tag that has a text field that its parameters call the scope. Any ideas?
First you need to create a form for searching..
<%= form_tag("/search") do %>
<%= text_field_tag :search %>
<%= submit_tag %>
<% end %>
In controller
def search
#results = AdminVerified.search(params[:search])
end
In view
<% #results.each do |r| %>
<%= r.field_1 %>
...
<% end %>
Hope this helps

Resources