rails_5 select and options_from_collections_for_select - ruby-on-rails

I am working in rails 5.
I am working with a database named "meals". Data base "meals" belongs to a database "events". I have the form_for with meals.
<%= form_for(meal) do |f| %>
I want to a create a drop down with information from database "Events" and then use that as an id for "meals". The dropdown is populated with "events" but i cannot get the event to be selected when I submit the form.
I am using the "select" combined with "options_from_collection_for_select".
</div>
<%= f.select :event_id, options_from_collection_for_select((events), "id", "name", "events.id" ), prompt: 'select' %>
</div>
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9RIvNLt92mYqM5P8m6l3t+vFiNwt/ISzr06pD+0xYlPR+eQR9E9FdsehIn TVwl6U/3q0UHCUw3epaUNuwMvfOw==", "meal"=>{"meal_name"=>"meal", "desc"=>"", "meal_type"=>"", "event_id"=>""}, "commit"=>"Create Meal"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
(0.1ms) begin transaction
(0.1ms) rollback transaction
Thank you!

Related

Why i can't create object with params?

I’ve been suffering from a problem for several days.
I can not create an object using the parameters from the form.
My form:
<%= form_with(model: #battle, local: true) do |form| %>
<div class="field">
<%= form.collection_select(:team_id, #teams, :id, :name) %>
</div>
<%= form.submit 'Submit'%>
<% end %>
In this form i want to choose only 1 team.
controller:
def create
#battle = Battle.new
#battle.user_id = current_user.id
#battle.team_ids = params[:team_id]
if #battle.save
redirect_to root_path, notice: "Battle has been created"
else
render :new
end
end
def battle_params
params.require(:battle).permit(:team_id)
end
And when used, this form creates an object without reference to the team.
logs:
Processing by BattlesController#create as HTML
Parameters: {"authenticity_token"=>"0wWoFrQXYkEsXsMRgGyKi5Mde7WndhI6zYWY4KvhQlgdcCAaCZqH1z1z9dK0x91iqOPw/Jsb2T6Q+EVtGz4VsA==", "battle"=>{"team_id"=>"14"}, "commit"=>"Submit"}
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/battles_controller.rb:14:in `create'
Team Load (0.4ms) SELECT "teams".* FROM "teams" WHERE 1=0
↳ app/controllers/battles_controller.rb:15:in `create'
(0.4ms) BEGIN
↳ app/controllers/battles_controller.rb:16:in `create'
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/battles_controller.rb:16:in `create'
Battle Create (3.8ms) INSERT INTO "battles" ("user_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["user_id", 1], ["created_at", "2020-06-19 10:28:28.036147"], ["updated_at", "2020-06-19 10:28:28.036147"]]
If I try to create a battle with two teams, but it will be created with only one (without using parameters):
#battle.team_ids = [params[:team_id], 14]
Although, a battle is created without problems in the console:
battle = Battle.new
battle.team_ids = [13, 14]
I don’t understand what the problem may be.
Instead of params[:team_id] try using battle_params[:team_id] instead:
#battle.team_ids = battle_params[:team_id]
otherwise you'd need to call params[:battle][:team_id] which is not the Rails way as it isn't as secure, but it would still work.

How to get results from a pg_search multisearch

I'm trying to use the pg_search gem in my rails application to search through numerous models from one search bar.
I have added the search bar:
<div id="search-bar">
<%= form_tag searches_path, method: :get do %>
<span><%= text_field_tag :query, params[:query] %><%= submit_tag "Search", name: nil %></span>
<% end %>
</div>
The route:
resources :searches
The searches controller index method:
def index
#results = PgSearch.multisearch(:query)
end
And the search index.html.erb:
<ul>
<% #results.each do |result| %>
<li><%= link_to result.searchable.title, result.searchable %></li>
<% end %>
</ul>
Each model that I want to be searchable has something like this in it:
include PgSearch
multisearchable :against => [:content, :author]
And I have an initializer like this:
PgSearch.multisearch_options = {
:using => {
:tsearch => {
:dictionary => "english"
}
}
}
I created a new item to make sure that it was added to the pg_search_documents table and checked the terminal to see that it was.
Yet when I enter a search query, nothing is coming up in the results table?
Here is the terminal output from the search:
Started GET "/searches?utf8=%E2%9C%93&query=Test" for 127.0.0.1 at 2019-01-16 13:16:48 +0000
Processing by SearchesController#index as HTML
Parameters: {"utf8"=>"✓", "query"=>"Test"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /Users/---/.rvm/gems/ruby-2.5.3/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Group Exists (0.2ms) SELECT 1 AS one FROM "groups" LIMIT $1 [["LIMIT", 1]]
↳ app/controllers/application_controller.rb:34
Category Exists (0.2ms) SELECT 1 AS one FROM "categories" LIMIT $1 [["LIMIT", 1]]
↳ app/controllers/application_controller.rb:37
Rendering searches/index.html.erb within layouts/application
ggPgSearch::Document Load (20.6ms) SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('english', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('english', ''' ' || 'query' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('english', coalesce("pg_search_documents"."content"::text, ''))) ## (to_tsquery('english', ''' ' || 'query' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC
↳ app/views/searches/index.html.erb:7
Rendered searches/index.html.erb within layouts/application (24.2ms)
Group Load (0.3ms) SELECT "groups".* FROM "groups"
↳ app/views/layouts/application.html.erb:59
Category Load (0.2ms) SELECT "categories".* FROM "categories"
↳ app/views/layouts/application.html.erb:72
Completed 200 OK in 114ms (Views: 88.4ms | ActiveRecord: 21.9ms)
The ul tags are present on the page, but no li items, and I am sure that the term I am putting in was within the item I created.
How come it isn't picking up any results? Many thanks
Did you do the following?
$ rails g pg_search:migration:multisearch
$ rake db:migrate
It's required for multisearching. Also existing items may not be added to the document as you already know. You would need to "rebuild" as stated in the docs. When you made a new item for testing, did you save it properly?
Here are the docs I found for the pg gem:
https://github.com/Casecommons/pg_search

RoR - ActiveAdmin Impossible to create a new product with nested form

I am new to rails and I'm trying to customize ActiveAdmin.
My app has 3 models: User (which has many products), Product (which has many prices) and Price. I am trying to customize ActiveAdmin with a nested form to be able to create/update a product directly with its prices.
Although the update works perfectly (updating product and even adding a new price), the create action doesn't work. I get "rollback" in the console but no specific error message.
Can you tell me what I'm doing wrong?
# app/admin/products.rb
ActiveAdmin.register Product do
form do |f|
f.semantic_errors
f.inputs do
f.input :name
f.input :size
end
f.inputs "Prices" do
f.has_many :prices do |price|
price.input :value
price.input :currency, :collection => ["dollars", "euros", "pounds"]
end
end
f.actions
end
permit_params :name, :size, :user_id, prices_attributes: [:id, :currency, :value, :product_id, :_edit, :_update, :_new, :_create]
I have also put "accepts_nested_attributes_for :prices" in app/models/product.rb.
The logs form the console
Started POST "/admin/products" for 127.0.0.1 at 2018-03-28 14:46:05 +0200
Processing by Admin::ProductsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"W9OJHqyFzXREfi4/DuBN1xnf0KIhAjJDfGsZjQqvGJ7BZOb11fVAz78djOf1k3XZdmpJxuPYinYi6Knu2agvnQ==", "product"=>{"name"=>"Shorts", "size"=>"XL", "prices_attributes"=>{"0"=>{"value"=>"40", "currency"=>"euros"}}}, "commit"=>"Create Product"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
AdminUser Load (0.4ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = $1 ORDER BY "admin_users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
(0.2ms) BEGIN
(0.3ms) ROLLBACK
Rendering /Users/alex/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/activeadmin-1.2.1/app/views/active_admin/resource/new.html.arb
Rendered /Users/alex/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/activeadmin-1.2.1/app/views/active_admin/resource/new.html.arb (100.1ms)
Completed 200 OK in 248ms (Views: 132.6ms | ActiveRecord: 1.9ms)
Thank you very much for you help.

How do I display a bootstrap modal in my case?

I am using bootstrap and I have a link that redirects to images#show action from home#index. The link is written in haml:
- url = #entry.class.to_s.downcase.singularize
= link_to(send("#{url}_path", #entry), data: { 'type' => #entry.class.to_s.downcase }) do
= yield
So currently, the home#index displays a list of images and when an image is clicked on, the link written above redirects the user to the view for the specific image Ex: images/1. That is to say that #entry represents the image and when clicked redirects to the specific image or (#entry).
I do not want to move away from the homepage (home#index), I just want to display a modal view that will take into account which images ( or #entry) was clicked on. How do I modify this link and add code that will display a bootstrap modal when the above link is clicked on ? What other steps should I follow ? I just need help to the point of displaying the modal.
Here is my trace:
Started GET "/images/3" for ::1 at 2016-09-07 22:28:10 -0400
Processing by ImagesController#show as */*
Parameters: {"id"=>"3"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Image Load (0.3ms) SELECT "images".* FROM "images" WHERE "images"."id" = $1 LIMIT 1 [["id", 3]]
Group Load (0.4ms) SELECT DISTINCT "groups".* FROM "groups" INNER JOIN "group_memberships" ON "groups"."id" = "group_memberships"."group_id" WHERE "group_memberships"."member_id" = $1 AND "group_memberships"."member_type" = $2 AND "group_memberships"."group_type" = $3 [["member_id", 1], ["member_type", "User"], ["group_type", "Group"]]
GroupMembership Load (0.4ms) SELECT "group_memberships".* FROM "group_memberships" WHERE "group_memberships"."member_id" = $1 AND "group_memberships"."member_type" = $2 [["member_id", 3], ["member_type", "Image"]]
GroupMembership Load (0.5ms) SELECT "group_memberships".* FROM "group_memberships" WHERE "group_memberships"."group_type" = $1 AND "group_memberships"."member_type" = $2 AND "group_memberships"."member_id" = $3 AND "group_memberships"."group_id" IN (-1, -1) [["group_type", "Group"], ["member_type", "User"], ["member_id", 1]]
Rendered images/_modal.html.erb (0.0ms)
Rendered images/show.js.erb (1.2ms)
Completed 200 OK in 27ms (Views: 10.0ms | ActiveRecord: 1.9ms)
One option is to use a js template and change your links to use use the remote: true option:
<%- #images.each do |image| -%>
<%= link_to '...', image_path(image) remote: true %>
<%- end -%>
<div id="modals"></div>
Next in the controller the response type can be set to js (probably a good idea to also keep the html option around):
respond_to do |format|
format.js
end
Then in the template that handles the js:
// app/views/images/show.js.erb
$("#modals").html('<%= j render "images/modal", image: #image %>');
$('#modals .modal').modal();
$('#modals .modal').modal('.toggle');
Finally add a partial for the modal and setup any markup needed:
<!-- app/views/images/_modal.html.erb -->
<div class="modal fade">
...
<%= image_tag(image.url, class: "img-responsive") %>
...
</div>

serialize a column and save

I'm using rails 4.2 with ruby 2.2.
I'm trying to save some data inside a column in a hash format.
I'm trying to save license details in the license column which is of text datatype, and in the respective model i've given:
serialize :license, JSON
I have this in the controller:
params.require(:company_detail).permit(:company_name, :trading_name, :contact_name, :acn, :address, :suburb, :state, :post_code, :phone_number, :fax_number, :nrma_approved, :start_date, :release_date , :website_url ,:email, license: {date1: :date1, license1: :license1, date2: :date2, license2: :license2, date3: :date3, license3: :license3, date4: :date4, license4: :license4})
and in form
= form_for #company_detail, remote: true, html: {class: 'form-horizontal form-label-left', data: {"parsley-validate" => ""}} do |f|
= f.fields_for :license do |l|
.row
.col-lg-6
.form-group
%label.control-label.col-md-4.col-xs-12 Date 1
.col-md-8.col-xs-12
= l.text_field :date1, value: #company_detail.license.present? ? #company_detail.license["date1"] : '', class: 'date-picker form-control has-feedback-left datePicker'
.col-lg-6
.form-group
%label.control-label.col-md-4.col-xs-12 Licence Number 1
.col-md-8.col-xs-12
= l.text_field :license1, value: #company_detail.license.present? ? #company_detail.license["license1"] : '', class: 'form-control'
I tried entering a few fields in the form and submit, but even though the params are going in correctly, the value saved is null. This is the log:
Parameters: {"utf8"=>"✓", "company_detail"=>{"license"=>{"date1"=>"121212", "license1"=>"12313", "date2"=>"122131123", "license2"=>"123123", "date3"=>"", "license3"=>"", "date4"=>"", "license4"=>""}}, "commit"=>"Save", "id"=>"1"}
CompanyDetail Load (0.3ms) SELECT "company_details".* FROM "company_details" WHERE "company_details"."id" = $1 LIMIT 1 [["id", 1]]
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(1.0ms) BEGIN
SQL (0.4ms) UPDATE "company_details" SET "license" = $1, "updated_at" = $2 WHERE "company_details"."id" = $3 [["license", "{\"date1\":null,\"license1\":null,\"date2\":null,\"license2\":null,\"date3\":null,\"license3\":null,\"date4\":null,\"license4\":null}"], ["updated_at", "2016-05-01 12:15:44.918547"], ["id", 1]]
Try this for your strong parameters for licence:
license: [:date1, :license1, :date2, :license2, :date3, :license3, :date4, :license4]
If you are using postgres as your db, then you can use json as the datatype for your column.
See here - ActiveRecord JSON
If you are looking into querying your json fields, you should use the jsonb field. Reference
But please note jsonb datatype was only introduced in postgresql v9.4

Resources