Date not saving within parameters of model - ruby-on-rails

within my view form, I currently have this code:
<div class="panel panel-default">
<div class= "panel-body">
<%= form_for #meal_plan, url: new_meal_plan_path, method: "GET", html: { class: "form-inline" } do |form| %>
<div class="form_group">
<%= form.label :start_date %>
<%= form.text_field :start_date, type: "date", class: "form-control" %>
</div>
<div class="form_group">
<%= form.label :end_date %>
<%= form.text_field :end_date, type: "date", class: "form-control" %>
</div>
<div class="form-group action">
<%= form.submit "Generate Plan", class: "btn btn-default"%>
</div>
<% end %>
</div>
</div>
That takes a start date and an end date input for a meal plan. In the new method within the meal_plan_controller, I have:
def new
puts params[:start_date]
puts params[:end_date]
#meal_plan = current_user.meal_plans.build(
start_date: params[:start_date] || Date.today,
end_date: params[:end_date] || 6.days.from_now.to_date,
)
#meal_plan.build_meals
end
In the puts statements that I wrote to debug, :start_date and :end_date contains only the default dates, so my guess is that the dates are not saving when the user hits submit, but I can't figure out why.

Related

Setting the end_time value the same as start_time value in a rails form

Rails 6.0.3
I am using a form to schedule meetings.
It is being used for both single time meetings that span over several days (with start_time and end_time) and tasks that last only one day.
For singular day meetings, I need the end_time to be set to the same value as start_time, without user selecting it.
I have tried many things in the controller, but can't work it out.
How would you go about this.
Thanks for the help
<div class="border border-grey-light rounded" style ="padding: 10px;">
<%= form_with(model: meeting, local: true, :html => {:id => "flatpickr-form-single"} ) do |form| %>
<div class="mb-6">
<%= form.label :name, class: 'label' %>
<%= form.text_field :name, required: true, class: 'form-control', placeholder: "Task name" %>
</div>
<div class="mb-6">
<%= form.label :body %>
<%= form.rich_text_area :body, class: 'form-control' %>
</div>
<div class="start_time_result mb-6" style ="width: 30vw;">
<%= form.label :start_time, class: 'label' %>
<div class="flex items-center justify-between max-w-md">
<%= form.text_field :start_time, data: { behavior: "flatpickr" }, placeholder: "Date and time select ...", class: "form-control" %>
</div>
</div>
<div class=" field" style ="width: 30vw;">
<%= form.label :end_time, class: 'label' %>
<div class="end_time_result flex items-center justify-between max-w-md" >
<%= form.text_field :end_time, data: { behavior: "flatpickr" }, placeholder: "Date and time select ...", class: "form-control required" %>
</div>
</div>
<%= form.submit class: "btn btn-primary text-base py-1.5 px-5", value: "Confirm" %>
<% end %>
</div>
<script>
const selectElement = document.querySelector('.start_time_result');
selectElement.addEventListener('change', (event) => {
const end_time_result = document.querySelector('.end_time_result');
end_time_result.textContent = `${event.target.value}`;
});
</script>
You can add a before_action in the controller and set the end_time parameter value to the same as the start_time from there.

Skyscanner Flight search API with Ruby on rails6

Hi i'm working on flight ticket website(search cheap flight ticket),using Skyscanner Flight API. Basically i copied this API tutorial to implement flight search function. However it only shows blank result in search.html.erb. In tutorial's form page you only fill out country name in form using different API. I'm stuck now and wonder how to implement search action & find_ticket action to take several parameter from index page's form and shows result properly.
Environment Rails:6.02 Ruby:2.65 RapidApi:skyscannerFlightSearch(i'm using RakutenRapidAPI)
Routes.rb
Rails.application.routes.draw do
root to: 'travel#index'
get '/search' => 'travel#search'
resources :messages
end
travel_controller.rb
class TravelController < ApplicationController
def index
end
def search
tickets = find_ticket(params[:country])
unless tickets
flash.now[:alert] = 'ticket not found'
return render action: :index
end
#ticket = tickets.first
end
private
def find_ticket(name)
request_api(
"https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/browsequotes/v1.0/#{URI.encode(name)}"
)
end
def request_api(url)
response = Excon.get(
url,
headers: {
'X-RapidAPI-Host' => URI.parse(url).host,
'X-RapidAPI-Key' => Rails.application.credentials.rapid[:XXXX_key]
}
)
return nil if response.status != 200
JSON.parse(response.body)
end
end
Views/travel/index.html.erb
<div class="container">
<div class="row">
<div class="col-lg-12 mt-5">
<% if flash[:alert] %>
<div class="alert alert-warning"><%= flash[:alert] %></div>
<% end %>
<div class="mx-auto mt-5" style="width: 400px">
<%= form_with(url: search_path, method: 'get', local: true) do %>
<div class="form-group">
<%= label_tag :country, 'country '%>
<%= text_field_tag :country, nil, placeholder: 'US', class: 'form-control' %>
<%= label_tag :currency, 'currency'%>
<%= text_field_tag :currency, nil, placeholder: 'USD', class: 'form-control' %>
<%= label_tag :locale, 'locale'%>
<%= text_field_tag :locale, nil, placeholder: 'en-US', class: 'form-control' %>
<%= label_tag :originplace, 'originplace'%>
<%= text_field_tag :originplace, nil, placeholder: 'SFO-sky', class: 'form-control' %>
<%= label_tag :destinationplace, 'destinationplace'%>
<%= text_field_tag :destinationplace, nil, placeholder: 'JFK-sky', class: 'form-control' %>
<%= label_tag :outbounddate, 'outbounddate'%>
<%= text_field_tag :outbounddate, nil, placeholder: '2020-02-01', class: 'form-control' %>
</div>
<%= button_tag 'Search', class: 'btn btn-success btn-block' %>
<% end %>
</div>
</div>
</div>
</div>
views/travel/search.html.erb
<div class="container">
<div class="row mt-5">
<div class="col-lg-6">
<h4>Ticket info</h4>
<dl>
<dt>PlaceId</dt>
<dd><%= #ticket['PlaceId'] %></dd>
<dt>lataCode</dt>
<dd><%= #ticket['IataCode'] %></dd>
<dt>Name</dt>
<dd><%= #ticket['Name'] %></dd>
<dt>SkyscannerCode</dt>
<dd><%= #ticket['SkyscannerCode'] %></dd>
<dt>CityName</dt>
<dd><%= #ticket['CityName'] %></dd>
</dl>
</div>
</div>
</div>
</div>

Duplicating a record in Rails except for one attribute?

In my Rails application I am getting the duplication of last Expense record after the creation of new record but I want to exclude one attribute while duplication that is :description_other, " ".
expenses_controller.rb
class ExpensesController < ApplicationController
# GET /expenses/new
def new
if Expense.last.present?
#expense = Expense.last.dup
else
#expense = Expense.new
end
end
def expense_params
params.require(:expense).permit(:date, :description, :description_other, :trips, :fare, :credit)
end
end
_form.html.erb
<div class="row">
<div class="col-md-3 col-md-offset-4">
<%= form_for(#expense) do |f| %>
<div class="form-group">
<%= f.label :date %><br>
<span class="datetime"><%= f.date_select :date %></span>
</div>
<div class="form-group">
<%= f.label :credit %><br>
<%= f.text_field :credit, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :description %><br>
<%= f.select(:description, options_for_select([['PLEASE SELECT...', ''],['METRO', 'METRO'], ['BUS', 'BUS'], ['TAXI', 'TAXI'], ['OTHERS', 'OTHERS'], ['FOOTLOOSE', 'FOOTLOOSE']]), {}, {class: "form-control", id: "expense_description"}) %>
<br>
<div id="otherDesc">
<%= f.text_field :description_other, class: "form-control" %>
</div>
</div>
<div class="form-group">
<%= f.label :trips %><br>
<%= f.number_field :trips, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :fare %><br>
<%= f.text_field :fare, class: "form-control" %>
</div>
<br>
<div style="margin-left: 70px;" class="form-group">
<%= f.submit #expense.new_record? ? "Create Expense" : "Update Expense", class: "btn btn-lg btn-primary" %>
</div>
<% end %>
</div>
</div>
I have tried but unable to get the desired result.
Any suggestions are most welcome.
Thank you in advance.
You should add
<div id="otherDesc">
<%= f.text_field :description_other, class: "form-control", value: " "%>
</div>
use tap and then exclude property by setting to nil
def new
if Expense.last.present?
# exclude here
#expense = Expense.last.dup.tap do | exp |
exp.description_other = nil
end
else
#expense = Expense.new
end
end

Rails - Search results are not filtered. Returning all availability

The task scope: A user selects an option from a drop down menu (Single/Double bedroom), clicks on search button and gets all related results. Then on the search page the user can further refine results by using available filters (TV/Shower). For some reason none of these actions modify the search results- the page displays all available listings in the database, rather than the ones that match the criteria..
What am I doing wrong?
Here is what I have so far:
HOME SEARCH BAR
<%= form_tag search_path, method: :get do %>
<div class="row">
<div class="col-md-7">
<%= select_tag :bedroom, options_for_select([['Single', 1], ['Double', 2]]), class: "form-control" %>
</div>
<div class="col-md-2">
<%= submit_tag "Search", class: "btn btn-normal btn-block" %>
</div>
</div>
<% end %>
SEARCH PAGE
<div class="col-sm-3">
<%= search_form_for #search, url: search_path, remote: true do |f| %>
<div class="row">
<div>
<%= check_box_tag "q[is_tv_eq]", true %> TV
</div>
<div>
<%= check_box_tag "q[is_shower_eq]", true %> Shower
</div>
</div>
<div class="row text-center">
<%= f.submit "Search", class: "btn btn-form" %>
</div>
<% end %>
<%= render partial: "rooms/rooms_list", locals: {rooms: #arrRooms} %>
</div>
ROOM LIST PARTIAL
<% rooms.each do |room| %>
<div class="row">
<%= image_tag room.cover_photo(:medium) %>
<%= link_to room.user_id, room %>
<%= room.price %> - <%= room.bedroom %>
<div id="star_<%= room.id %>"></div> <%= pluralize(room.average_rating, "review") %>
</div>
<script>
$('#star_<%= room.id %>').raty({
path: '/assets',
readOnly: true,
score: <%= room.average_rating %>
});
</script>
<% end %>
ROOM MODULE
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.string :bedroom
t.integer :price
t.boolean :active
t.timestamps
end
end
end
PAGE CONTROLLER
def search
# STEP 1
if params[:search].present? && params[:search].strip != ""
session[:loc_search] = params[:search]
end
# STEP 2
if session[:loc_search] && session[:loc_search] != ""
#rooms_bedroom = Room.where(active: true, bedroom: session[:loc_search]).order(:price)
else
#rooms_bedroom = Room.where(active: true).all
end
# STEP 3
#search = #rooms_bedroom.ransack(params[:q])
#rooms = #search.result
#arRoooms = #rooms.to_a
end
DEFINED THE BEDROOM OPTIONS IN THE ROOM OVERVIEW PAGE (not sure if that helps)
<%= form_for #room do |f| %>
<div class="form-group">
<label> Bedroom Type </label>
<%= f.select :bedroom, [["Single", "Single"], ["Double", "Double"]],
id: "bedroom", prompt: "Select...", class: "form-control" %>
</div>
</div>
<div><%= f.submit "Save", class: "btn btn-normal" %></div>
<% end %>
Thanks

Rails - getting the value out from the view form into a controller

In my form the user has to select a category for his post.
<div class="field form-group">
<%= f.text_field :category, class: "form-control" %>
</div>
(Currently I am using text-input instead of a drop-down list)
Posts belong to categories
#post = #category.posts.build(post_params)
However I can't understand how to get the category value out of that field.
I have tried passing a number, to find_by id, and string to find_by name.
#category = Category.find(params[:category]) #returns no Categoy with nil id
#category = Category.find_by(name: params[:category]) #returns no method error
any help would be appreciated
Edit:
Form code
<%= form_for [#company, #post], :html => { :class => "form-posts"} do |f| %>
<div class="field form-group">
<div class="input-group input-group-lg">
<span class="input-group-addon">$</span>
<%= f.text_field :text, class: "form-control", placeholder: "text", required: true %>
</div>
</div>
<div class="field form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar"></i>
</span>
<%= f.text_field :date,
class: "form-control",
value: #today,
data: {behaviour: "datepicker"},
required: true %>
</div>
</div>
<div class="field form-group">
<%= f.text_field :comment, class: "form-control", placeholder: "Comment (optional)" %>
</div>
<div class="field form-group">
<%= f.text_field :category, class: "form-control" %>
</div>
<div class="actions"><%= f.submit 'Add', class: "btn btn-lg btn-primary" %></div>
<% end %>
Edit 2
controller:
form:
<%= f.text_field :category, class: "form-control" %>
def create
#company = current_user.companies.find(params[:company_id])
#category = #company.categories(params[:category])
#post = #category.posts.build(post_params)
debugger:
{"utf8"=>"✓", "authenticity_token"=>"...", "transaction"=>{"text"=>"lalala", "date"=>"11.11.2013", "comment"=>"", "category"=>"5"}, "commit"=>"Add post", "action"=>"create", "controller"=>"posts", "company_id"=>"2"}
undefined method `transactions'
Take a look at the development log.
Probably it will be something like params[:post][:category]
Get your category like this:
params[:post][:category]

Resources