checkbox in form associated with Model in Ruby on rails - ruby-on-rails

I have a Model "Startup" and I have a other Model "Categorie". The two tables are associated.
I'd like call the data of Categoria through to form of Startup, this categories displayed with a checkbox. Inside the form Startup Form I have the categorie_id. This is the code
<%= form_for(#startup) do |f| %>
<% if #startup.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#startup.errors.count, "error") %> prohibited this startup from being saved:</h2>
<ul>
<% #startup.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.collection_select :round_id, Round.order(:name), :id, :name, include_blank: true %>
</div>
<div class="field">
<%= f.label :category %><br />
<%= f.text_field :category_id %>
</div>
<div class="field">
<%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
</div>
<div class="actions">
<%= f.submit %> </div> <% end %>
How to display the data of Categories within form with a checkboxs ?
Any idea.
pdt: My english is really bad.

If a Startup can have only one Category, you can do like this in your view:
<div class="field">
<%= f.label :category %><br />
<%= f.collection_select :category_id, Category.all, :id , :name %>
</div>
This will output a dropdown menu with all the categories. Make sure that the Category model has the attribute name.
As you said, a Startup belongs to one Category, so using radiobuttons (checkboxes are here for multiple relation, means you could choose multiple categories):
<div class="field">
<% Category.all.each do |category| %>
<%= f.radio_button :category_id, category.id %>
<%= f.label :category_id, category.name %>
<% end %>
</div>
You may have to add <br /> tags, and html options to make it looks better.

As MrYoshiji says, you can use:
It will display the category name on the screen, and the value sent will be the id.
You can find more details here : http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
I advise you to use the simple_form gem to generate your form. It's a very simple gem to use and customize ! look at it ;)

Related

Attempting to utilize a drop down menu in a form in ruby on rails

First off, I'm pretty new to Ruby and Ruby on rails, so bear with me.
I'm attempting to have my categories section of my form utilize my category table in my db so that when the author wants to select on a category, they can just select the drop down menu and choose one. For now, I've hard coded them and this works
<%= form_for(#article) do |f| %>
<% if #article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% #article.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.label :author_id %><br>
<%= f.text_field :author_id %>
</div>
<div class="field">
<%= f.label :category_id %><br>
<%= f.select (:title), [['Finance'], ['Marketing'], ['Programming'], ['Leisure'], ['Management'], ['Food']] %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
but, by switching the categories section to
<div class="field">
<%= f.label :category_id %><br>
<%= f.select :category_id, Category.all %>
</div>
it will give me a drop down box containing each hash, and I'm not to sure why, but I can't do Category.all.name to get the names (I'm assuming it is because it's in a hash). Any help would be great appreciated.
It looks like that you need to change you select use options_for_select tag:
<%= f.select :category_id, options_for_select(Category.all.collect {|c| [ c.name, c.id ] }), :include_blank => true %>
if you want to pre-populate category_id
<%= f.select :category_id, options_for_select(Category.all.collect {|c| [ c.name, c.id ]}, #article.category_id), :include_blank => true %>
For more information options_for_select
Have you defined the Category model in your Controller? The form can/will only know what the controller knows. It cannot know any more. If this form is attached to the articles_controller then it will have access to #article, but it won't have access to #category.
So this leaves you with a couple options. Define category somewhere in your controller, OR alternatively (and this would be my suggestion) setup some type of association for your Articles model.
Does Article have many Categories? This is a great opportunity to setup that has_many association, and then you can access the category model via Article's associations methods.
This is my suspicion, but we really don't have enough information here. Can you post your controller, and your article model so we can see everything that is going on? Also, what error do you get specifically?

Radio button data not saved

I'm playing around with Form Helpers. I found some code from another SO question and thought it was pretty efficient at creating radio buttons with an elegant loop. Now that I've incorporated it, it doesn't save the data (e.g. the category value is not being saved to the project table)
Please see code below of _form.html.erb
<%= form_for(#project) do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% #project.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="form_row">
<label for="category">Category:</label>
<% [ 'checklist', 'process'].each do |category| %>
<br><%= radio_button_tag 'category', category, #category == category %>
<%= category.humanize %>
<% end %>
<br>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Your radio button parameter is being created outside of the project structure. If you look at params, you'll probably see
{:category => "your_category", :project => {...project params...}}
It is because you're using the radio_button_tag instead of the regular form helper. Try this instead:
f.radio_button :category, category, :checked => (#category == category)
Also, as Justin said, make sure :category is included in the project_params in your controller.

Rails - Displaying Foreign Key References in a form

I'm doing a simple exercise with two models. Sport and Teams, defined as
rails g scaffold sport name:integer
rails g scaffold team name:integer fans:integer sport:references
(Note: The reason I'm using scaffold is rapidly prototyping so I can learn/experiment with the parts I'm not familiar with yet)
Problem is that my "sport" (i.e. the foreign key reference) is showing like the following
So it's got that weird #<blahl blah> notation to it...
<%= form_for(#team) do |f| %>
<% if #team.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#team.errors.count, "error") %> prohibited this team from being saved:</h2>
<ul>
<% #team.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :fans %><br />
<%= f.number_field :fans %>
</div>
<div class="field">
<%= f.label :sport %><br />
<%= f.text_field :sport %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I've tried changing the one line to #team.sport.name but it results in an error undefined method 'Ice Hockey' for #<Team:0x3e7e040>... Any ideas how to properly display name from here??
You are using a text_field for referencing an existing object, a select with Sports as options would be more appropriate here.
This is where it has to be changed:
<div class="field">
<%= f.label :sport %><br />
<%= f.text_field :sport %>
</div>
To:
<div class="field">
<%= f.label :sport %><br />
<%= f.select :sport_id, options_for_select(Sport.all.map{|s|[s.name, s.id]}) %>
</div>
The f.select will generate a select box in HTML, the options will me all the sports in your DB.
Some documentation about it:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
http://guides.rubyonrails.org/form_helpers.html#select-boxes-for-dealing-with-models
A cleaner way would be to set a variable #sports in your controller and call it then in your views:
# in controller
def edit
#sports = Sport.scoped
#...
# in edit view
<div class="field">
<%= f.label :sport %><br />
<%= f.select :sport_id, options_for_select(#sports.map{ |s| [s.name, s.id] }) %>
</div>
Additionnal information: If you want to "pre-select" an option for the select, you have to pass it as the second argument of the options_for_select helper:
options_for_select(#sports.map{ |s| [s.name, s.id] }, params[:sport_id])
# this will select by default the option that matches the value of params[:sport_id]

undefined method for form fields

I'm working on a advanced search form. I am working in views/searches. Now I have attributes created for user profiles that I have been using such as zip code, age, gender, career, religion, education, etc. I want to use these fields for my advanced search.
When I include the f.label and text fields I get a undefined method. I'm hoping I don't have to recreate each attribute for the search form, as that would not make much sense considering I have already done all these attributes for the user profile. Any help would be greatly appreciated!
/searches/new.html (for search):
<%= form_for #search do |f| %>
<div class="field">
<%= f.label :keywords %><br/>
<%= f.text_field :keywords%>
</div>
<div class="field">
<%= f.label :zip_code %><br/>
<%= f.text_field :zip_code %>
</div>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>
/users/new.html (for the user profile):
<%= form_for #user do |f| %>
<% if #user.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email %><br/>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br/>
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :username %><br/>
<%= f.text_field :username %>
</div>
<div class="field">
<%= f.label :zip_code %><br/>
<%= f.text_field :zip_code %>
</div>
</div>
<div class="field">I'm a
<%= f.select :gender, ['man', 'woman']%>
interested in
<%= f.select :gender, ['women', 'men', 'both']%>
</div>
<div class="field">
Age <%= select(#object, :age, (18..75).to_a) %> to <%= select(#object, :age, (18..75).to_a) %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
Your #search object is a Search object (or whatever it actually is), not a User.
Rails doesn't know your Search object doesn't actually have those fields, so when it tries to retrieve the fields that don't exist, it'll blow up.
There are any number of ways around this, including giving your Search a User property.
You could also create a new User and pass it to a user form partial as f, that's probably the approach I would take, although I don't know precisely what it would look like without trying it.

Rails - add an array of another class on a form

I apologise if the question is quite simple, I'm fairly new to Rails. I'm building a meal planner application, and am trying to have it so that a user can create a meal, and add items to that meal. E.g. a meal of 'fish & chips' would include the items 'fish' and 'chips'. As I understand it, I think I need a way of creating an array of items on the meal creation form - but how do I do that?
Relevant parts of meal.rb:
has_many :items
accepts_nested_attributes_for :items
and item.rb
belongs_to :meal
What do I need to add to the meal form partial for it to accept an array of items? I apologise, I have no idea where to start! Alternatively, if there is a simpler way of doing it, please let me know. But I don't want to have a list of 'item_1_id', 'item_2_id' etc on the meal!! Thanks!!
<%= form_for(#meal) do |f| %>
<% if #meal.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#meal.errors.count, "error") %> prohibited this meal from being saved:</h2>
<ul>
<% #meal.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :category %><br />
<%= f.text_field :category %>
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :child_id %><br />
<%= f.number_field :child_id %>
</div>
<div class="field">
<%= f.label :time %><br />
<%= f.date_select :time %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
There is a great railscast episode that covers this. Also, you would want to use javascript to have a "add item" link. This example below, will always have one new item available.
You would want to do something like this
view
<%= f.fields_for :items do |builder| %>
<fieldset>
</fieldset>
<% end %>
controller
#meal.items.build
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2

Resources