ruby - text parse issues when populating from database - ruby

tried to create simple dropdown in ruby with values from the database - like that :
<% ingredientArray = Ingredient.all.map { |ingredient| [ingredient.name, ingredient.id] } %>
<div class="field">
<%= select_tag(:ingredient_id, ingredientArray) %><br/>
</div>
and I received an empy one.
this is the generated html
<div class="field">
<select id="ingredient_id" name="ingredient_id">[["Paprika", 5], ["Cinnamon", 8], ["Salt", 9], ["Pepper", 10], ["water", 11]]</select><br/>
</div>
where should I put html sage

You should read documentation on select_tag and related methods.
The second parameter of it is a string containing the option tags for the select box.
You can generate in manually:
select_tag "people", "<option>David</option>".html_safe
Or use options_from_collection_for_select method for it:
select_tag "people", options_from_collection_for_select(#people, "id", "name")
(Examples from the docs)
Specifically in your case the best way to make that dropdown is:
<div class="field">
<%= select_tag("Ingredients", options_from_collection_for_select(Ingredient.all, 'id', 'name')) %>
</div>

You can also use collection_select like so:
<%= collection_select :recipe, :ingredient_id, Ingredient.all, :id, :name, { prompt: "– Select an Ingredient –".html_safe } %>
(I've assumed the parent object you are trying to assign the ingredient ids to is :recipe. Change that value as it fits your app.)

Related

Get index of element in "element_view_for" helper in Alchemy CMS

I want to use a bootstrap 5 carousel in an alchemy element with nested images. In order to do this, i need to get the sortorder or index of the iteration, as the carousel expects an "active" tag on the first element.
<%= element_view_for(image_slide, tag: false) do |el| %>
<div class="carousel-item active">
<%= el.render :image, {}, class: "d-block w-100 #{"active" if index == 0}" %>
</div>
<% end %>
How can i achieve this?
In every Rails partial that rendered by the collection renderer you have a local variable called <the-partial-name>_counter available.
From https://guides.rubyonrails.org/layouts_and_rendering.html#local-variables
Rails also makes a counter variable available within a partial called
by the collection, named after the title of the partial followed by
_counter. For example, when rendering a collection #products the partial _product.html.erb can access the variable product_counter
which indexes the number of times it has been rendered within the
enclosing view. Note that it also applies for when the partial name
was changed by using the as: option. For example, the counter variable
for the code above would be item_counter.
Just make sure that the parent element (I'm assuming an imager_slider) uses the collection partial renderer.
[...]
<%= render image_slider.nested_elements.published %>
[...]
Then you can use
<%= element_view_for(image_slide, tag: false) do |el| %>
<div class="carousel-item active">
<%= el.render :image, {}, class: "d-block w-100 #{"active" if image_slide_counter == 1}" %>
</div>
<% end %>

Rails sending multiple params through dropdown box

I have two dropdown boxes. One is for campaign size(small, medium, large) and the other one is for the theme selection.
I want to be able to send params dynamically through onchange event handler
current code looks like this
<div class="col-lg-12 col-padding-helper">
<%= form_tag product_builder_path, method: :get do %>
<div class="col-lg-5 col-padding-helper">
<%= label_tag 'Campaign Size' %></br>
<%= select_tag 'type', options_for_select(['Small (4 Products)', 'Medium (7 Products)', 'Large (10 Products)' ]), multiple: false, :include_blank => true, class: "form-control", data: { remote: true }, onchange: "this.form.submit();" %>
</div>
<% end %>
<%= form_tag(product_builder_path, method: :get, remote: true) do %>
<div class="col-lg-7 col-padding-helper">
<%= label_tag 'Theme' %></br>
<%= select_tag 'theme', options_for_select(['Default BWX Theme', 'Black Friday Theme']), multiple: false, :include_blank => true, class: "form-control", onchange: "this.form.submit();" %>
</div>
<% end %>
</div>
The workflow that I am thinking in my head is that once user selects the campaign size it will submit a form through ajax and have something like this as a url. which then I can display display right type of html template on the webpage.
/product_builder?type=small
and after when they select the theme is it possible to do something like this? and this will change the theme of the type that I have chosen above
/product_builder?type=small&theme=black
so basically it's adding params to current URL
I don't even know if this is possible, any help or guidance would be awesome
Thank you

My Search returns an empty array

I am trying to make a search bar in order to find some cocktails by their name in my index. All I got is an empty array...
I believe my SQl request is not good... I'd need help please to make it working. Regards
Here is my code:
Search form:
<%= simple_form_for :query, url: cocktails_path, :method => :get do |f| %>
<%= f.input :search %>
<%= f.button :submit %>
<% end %>
cocktails controller:
def index
if params[:query].present?
#cocktails = Cocktail.all
#cocktail_search = #cocktails.where('cocktails.name LIKE ?', params[:query][:search])
binding.pry
else
#cocktails = Cocktail.all
end
end
the index view:
<% if #cocktail_search %>
<% #cocktail_search.each do |cocktail| %>
<div class="col-xs-12 col-sm-3">
<div class="card" style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.2)),
url('<%= cl_image_path cocktail.photo %>');">
<h2 class="card-description"><%= link_to cocktail.name, cocktail_path(cocktail)%></h2>
</div>
</div>
<% end %>
<% else %>
<% #cocktails.each do |cocktail| %>
<div class="col-xs-12 col-sm-3">
<div class="card" style="background-image: linear-gradient(rgba(0,0,0,0.3), rgba(0,0,0,0.2)),
url('<%= cl_image_path cocktail.photo %>');">
<h2 class="card-description"><%= link_to cocktail.name, cocktail_path(cocktail)%></h2>
</div>
</div>
<% end %>
<% end %>
This is my binding pry
#cocktail_search = #cocktails.where('cocktails.name LIKE ?', params[:query][:search])
If your table has column "name", then:
#cocktail_search = #cocktails.where('name LIKE ?', params[:query][:search])
should do the work.
When you're uncertain about what is wrong you can rails console and check things yourself, ex. Coctail.where("name like ?", "Mojito") and see if it returns expected result.
Since you use LIKE it seems like you want to find cocktails every if the search term matches only parts of the name. This can be archived by using % (see: Safe ActiveRecord like query).
Furthermore you might want to use a case-insensitive ILIKE instead of LIKE:
#cocktails.where('name ILIKE ?', "%#{params[:query][:search]}%")
Without the % you query is basically the same as
#cocktails.where(name: params[:query][:search])
that only returns exact matches.

How to get parameters value in model from views form in rails?

Here is my new.html.erb
<%= form_for :simulation, url: simulations_path do |f| %>
<div class="form-group">
<%= f.label :Name %>
<div class="row">
<div class="col-sm-2">
<%= f.text_field :name, class: 'form-control' %>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :'Rendering Option' %>
<div class="Dropdown">
<div class="col-sm-4">
<%= select_tag(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<%= f.submit 'Submit', class: 'btn btn-primary' %>
</div>
simulations_controller.rb
class SimulationsController < ApplicationController
def index
#simulations = Simulation.all
end
def new
end
def create
#simulation = Simulation.new(simulation_params)
#simulation.save
redirect_to #simulation
end
def show
#simulation = Simulation.find(params[:id])
end
end
Simulation.rb (Model class)
class Simulation < ActiveRecord::Base
belongs_to :user
end
Schema.rb
create_table "simulations", force: :cascade do |t|
t.string "name"
t.boolean "is_random"
end
I am not able to set the :is_random value in database while rest is fine. What I am doing wrong here? I checked the value in sqlite database and there was null entry in is_random column.
You need to permit attributes while doing mass assignment. You could write it as :
<%= f.select(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
or
<%= select_tag("simulations[:is_random]", options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
With your syntax, the value is inside the params hash as {..., is_random: true,..}, that's why inside the strong parameter filtering method you are not getting it. If you use now the suggested solutions, you will get it the value inside the params hash like {..., simulations: { is_random: true,..}, ...}.
You can inspect all these from the the development.log file, while making the request.
You need to use form object select method like bellow:
<%= f.select(:is_random, options_for_select([['Random', true], ['No Opinion', false]], selected: :is_random )) %>
Using f.select (suggested above) should fix your problem. If you look at the generated html, you will see this field with a name of "is_random". It should be "simulations[is_random]". When you pull the form field values from the params object like this params[:simulations] all form fields with names in the form of "simulations[name]" will be included. Using the form builder object names the form fields correctly.
Hope this helps!
You can also use <%= debug params %> to inspect what's in params, it's very helpful.

How to create dropdown list values depending on previous input?

I need some help on rails forms. I currently have:
<div class="field">
<%= f.label :student_id %>
<%= f.collection_select(:student_id, Student.active.order('first_name'), :id, :proper_name, :prompt => true) %>
</div>
<br />
<div class="field">
<%= f.label :section_id %>
<%= f.select(:section_id, get_section_list, :prompt => "Select Section") %>
</div>
So the first drop down is to select a student. The second drop down list is to select a section. However, right now I am displaying all sections. But I want to only the select those sections that the student is eligible for. So how do I get the input of the first drop down list in order to change the second drop down list options. If they try to choose the section without selecting a student, it should show all the options.
Thanks!
Put the select box in a partial and re-render the partial when the first select box changes.
http://keithschacht.com/getting-ajax-to-work-in-rails-3-with-jquery/

Resources