Rails - sql commands not working with datetime - mysql

I have a strange problem with my web app.
I am trying to build a simple reservation system for a game like "Escape the room". For now I made my own calendar looking a railscast (Calendars revised) for having the dates.
For the possible hours I made a new model and a new table in the database
t.integer "id"
t.datetime "start_time"
t.datetime "end_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
In the view I have something like this:
<%= calendar #date do |date| %>
<%= date.day %>
<table class="table">
<tbody>
<% #hours.each_slice(2) do |hour| %>
<tr>
<% hour.each do |h| %>
<td>
<%= link_to h.start_time.strftime('%H:%M'), new_escape_path(date: date, start_time: h.start_time.strftime('%H:%M'), end_time: h.end_time.strftime('%H:%M')) %>
</td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<% end %>
And I write these parameters into the database passing them in a form where user can complete other fields manually:
<%= text_field_tag :date, params[:date] %><br>
<%= text_field_tag :start_time, params[:start_time] %> do
<%= text_field_tag :end_time, params[:end_time] %>
The problem is that in the view I want to show only the hours which are not reserved yet, which means that they are not in the escapes table.
When in the console I write
Escape.all
I have something like:
#<Escape id: 1, date: "2015-08-11 00:00:00", start_time: "2015-08-10 08:30:00", end_time: nil, user_id: nil, created_at: "2015-08-10 15:26:14", updated_at: "2015-08-10 15:26:14">
but when I write
Escape.all.where(date: "2015-08-11 00:00:00")
it returns an empty record
#<ActiveRecord::Relation []>
I tried also to insert something like this in the view, but it's not working:
<% if Escape.where(["date = ? and start_time = ?", "#{date}", "#{h}"])%>
<%= h.start_time.strftime('%H:%M') %>
<% else %>
<%= link_to h.start_time.strftime('%H:%M'), new_escape_path(date: date, start_time: h.start_time.strftime('%H:%M'), end_time: h.end_time.strftime('%H:%M')) %>
<% end %>
Do you have any ideas? What am I doing wrong?

Related

Rails radio_buttons multiple selection for same attribute, is it possible?

I have a search_form_for and I need to be able to select multiple Payment statuses to make a Ransack search.
We already have an f.select dropdown box for this attribute, but we now need to be able to select more than one status at the same time.
form:
<%= search_form_for #search, url: admin_payments_path, html: {class: "form-inline"} do |f| %>
<div class="form-group">
<%= f.select :status_eq, payment_status_selector, { include_blank: "Payment status.."}, class: "form-control gray" %>
</div>
<% end %>
I've tried:
<%= f.select :status_eq, payment_status_selector, {include_blank: false}, {multiple: true, as: :radio_buttons} %>
gives me a select box with all the options allowing me to select multiple, but they are not radio_buttons and an empty value "" is passed along with the selected options.
<% payment_status_selector.each do |status| %>
<%= radio_button_tag :status_eq, "#{status[1]}", false, class: 'radio-checkbox' %>
<%= label_tag( "#{status[0]}") %>
<% end %>
This gives me a radio_button for each possible status, but I can't select more than one.
I can't figure out the correct way to do it. Maybe with check_boxes are a better option to be able to select/unselect statuses?
Yes, using check_box will be a better option.
Try,
<% payment_status_selector.each do |status| %>
<%= f.check_box :payment_statuses, { multiple: true }, status, false %>
<%= label status %>
<% end %>
And you can expect the values in controller from params as:
{ search: { payment_statuses: ["status 1", "status 2"] }
make sure that payment_status_selector returns array of values.
Hope that helped.
Reference: https://medium.com/programming-problem-solving-logbook/rails-multiple-checkboxes-e9c4c7fda356

Rails: How to let user input define how many entries are recorded into the database?

I am new to Rails. I am developing a web application where a user inserts inventory of shoes. So the user enters style code, size, price, and quantity. I want quantity to define how many entries there are in the database. So, if the quantity is three, three separate rows would be created for each shoe. Currently each form submission creates one row in the database.
My create in my shoe_controller:
def create
#shoe = Shoe.new(shoe_params)
respond_to do |format|
if #shoe.save
format.html { redirect_to #shoe, notice: 'Shoe was successfully created.' }
format.json { render :show, status: :created, location: #shoe }
else
format.html { render :new }
format.json { render json: #shoe.errors, status: :unprocessable_entity }
end
end
end
My _form.html.erb
<%= form_with(model: shoe, local: true) do |form| %>
<% if shoe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(shoe.errors.count, "error") %> prohibited this shoe from being saved:</h2>
<ul>
<% shoe.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :sku %>
<%= form.text_field :sku %>
</div>
<div class="field">
<%= form.label :size %>
<%= form.text_field :size %>
</div>
<div class="field">
<%= form.label :quantity %>
<%= form.number_field :quantity %>
</div>
<div class="field">
<%= form.label :price %>
<%= form.text_field :price %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
What changes would I need to make to achieve the result I am looking for?
Thanks!
#rohit is correct in that using the Shoe.create method will get you what you want. But to implement this, you can change your controller to the following. I'm sure there are much cleaner ways of doing this, but it should get you what you're looking for. Also, I would suggest validating the quantity in shoe_params is a positive integer.
def create
#show = Show.new(shoe_params)
# This will create an array of shoes from your params
new_shoes = (1..shoe_params[:quantity]).collect { Shoe.new(shoe_params) }
# Save each record and put the result in an array
success = new_shoes.map(&:save)
if success.all?
# all records saved
else
# maybe #shoe.valid? is false or something else happened
end
end
you can use ActiveRecord::Persistence#create, which can accept an array of hashes as a parameter.
Suppose quantity is three, so build the 3 new hash which will contain your records.
shoes_params = [
{
code: 1,
size: 8,
price: 300,
quantity: 1
},
{
code: 1,
size: 8,
price: 300,
quantity: 1
}, ...
]
Shoe.create(shoes_params)

Don't show the timestamp & info on iterate

No idea why this is showing the entire table. Should only be showing the list and not the table (timestamp, id, etc).
Screenshot of output.
show.html.erb
<h1><%= #application.name %></h1>
<h4><%= #application.description %></h4>
<h3>Questions</h3>
<ul>
<%= #application.tests.each do |test| %>
<li>
<%= test.question %>
</li>
<% end %>
</ul>
schema.rb
create_table "tests", force: :cascade do |t|
t.string "question"
t.integer "application_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["application_id"], name: "index_tests_on_application_id", using: :btree
end
new to this whole "coding" thing
The problem is in the #application.tests.each you are printing the return, change:
<%= #application.tests.each do |test| %>
For
<% #application.tests.each do |test| %>
<% %> and <%= %> both execute Ruby code.
<% %> will execute Ruby code, but will not render the return value into html. <%= %> will execute Ruby code, and will render the return value into html.
So use like this :-
<% #application.tests.each do |test| %>
<li>
<%= test.question %>
</li>
<% end %>

Conditionally setting html parameters in Rails

I have a pair of radio buttons that I want to pre-assign a checked value to only my new action. Right now I'm conditionally rendering two partials. One partial that has radio buttons with checked attributes and the other with not attributes at all:
<%= form_for([#restaurant, #dish_review], url: :restaurant_dish_reviews) do |f| %>
<% if action_name == "new" %>
<%= render "status_buttons_checked", f: f, dish: #dish %>
<% else %>
<%= render "status_buttons", f: f %>
<% end %>
<% end %>
_status_buttons_checked
<div class="field">
<%= f.radio_button :status, :upvoted, checked: current_user.voted_up_on?(dish) %>
<%= f.label :status, value: :upvoted %>
<%= f.radio_button :status, :downvoted, checked: current_user.voted_down_on?(dish) %>
<%= f.label :status, value: :downvoted %>
</div>
_statsus_buttons
<div class="field">
<%= f.radio_button :status, :upvoted, checked: current_user.voted_up_on?(dish) %>
<%= f.label :status, value: :upvoted %>
<%= f.radio_button :status, :downvoted, checked: current_user.voted_down_on?(dish) %>
<%= f.label :status, value: :downvoted %>
</div>
I was wondering if there was any way in Rails where I can insert the conditional in the radio_button parameter instead of creating two partials. I'd like to something similar to what's show below but run into a template error:
<%= f.radio_button :status, :downvoted, if action_name == "new" current_user.voted_down_on?(dish) %>
When using form_for, the form methods you use are automatically populated with the appropriate data for your attributes. Whilst I don't know if this works with the checked value, it means that if you have the following:
<%= form_for #user do |f| %>
<%= f.text_field :name %>
<% end %>
... :name will be populated from your #user object (if it's new, no data will be inserted).
--
This means that if you're using form_for, you should be able to populate the checked value with the data passed to the view:
<%= form_for [#restaurant, #dish_review] do |f| %>
<%= f.radio_button :status, :upvoted, checked: current_user.voted_up_on? #dish %>
<%= f.radio_button :status, :downvoted, checked: current_user.voted_down_on? #dish %>
<% end %>
I don't see what you're trying to achieve from your partials (they're both the same) -- but if you wanted to create "checked" on conditions, you'd be able to use the following:
<%= checked = action_name == "new"
<%= f.radio_button :status, :downvoted, checked: checked %>
This will set the value as "true" or "false" depending on whether the action is new or not.

Difference between collection_select and collection_checked_boxes

new.html.erb
Price: <%= f.collection_select :price_ids, Price.all, :id,:name,prompt: true %> JD
In the controller:
def dress_attributes
dress_attributes = params.require(:dress).permit(:name,:email,:phone,:description,:image,:image2,[:price_ids: []})
end
In show.html.erb:
Price: <% #dress.prices.each do |s| %>
<%= s.name %>
<% end %>`
And the price doesn't show.
What's wrong when I change the collection_select to collection_checked_boxes? It works, but I want the collection_select.
You can pass multiple: true as html_options to collection_select as given below.
new.html.erb
Price: <%= f.collection_select :price_id, Price.all, :id,:name, {prompt: true}, {multiple: true} %> JD
In the controller
def dress_attributes
dress_attributes = params.require(:dress).permit(:name,:email,:phone,:description,:image,:image2,:price_id)
end
Then, in your controller, you can access price_id as params[:dress][:price_id] which will be an array of selected prices.