How do I submit one param multiple times on rails? - ruby-on-rails

So I have Users and Interests and they are associated with a has_and_belongs_to_many relation through an interests_users table. What I want to do is to let users select 5 interests when they create their account through checkboxes, but I don't now how to submit the same param 5 times in the same form and I am currently submiting it with checkbox, but Interest is not a boolean. The code right now is like this:
<div class = "field">
<%= f.label :interests %><br>
<% all_interests = Interest.all.map{ |f| [f.name, f.id] } %>
<% all_interests.each do |interest| %>
<p> <%= interest[0] %> <%= f.check_box :interests %> <p>
<% end %>
</div>

In view use the flowing
<% for interest in Interest.all %>
<%= check_box_tag "user[interest_ids][]", interest.id, #user.interests.include?(interest) %>
<%= interest.name %>
<% end %>
In controller accept params as following
params.require(:user).permit( { interest_ids:[] })

You should try this code :
<div class = "field">
<%= f.label :interests %><br>
<% Interest.all.each do |interest| %>
<p> <%= interest.name %> <%= f.check_box :interests, { :multiple => true }, interest.id, nil %> </p>
<% end %>
</div>

Related

How to create a view containing field of an associated model in rails?

In my project, I have an Organization model and an Address model. Here is the association beetween the models:
class Organization < ApplicationRecord
belongs_to :adresse
end
class Organization < ApplicationRecord
has_one :organization
end
I would like to know how to create a new form and include attributes from both model. For the moment, my organization/new.html.erb look like this:
<%= form_with(model: organization, local: true) do |form| %>
<% if organization.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(organization.errors.count, "error") %> prohibited this organization from being saved:</h2>
<ul>
<% organization.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :organizationName%>
<%= form.text_field :organizationName, id: :organization_organizationName %>
</div>
<div class="field">
<%= form.label :email %>
<%= form.text_field :email, id: :organization_email %>
</div>
<div class="field">
<%= form.label :website %>
<%= form.text_field :website, id: :organization_website %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
And I tried to add this to the form but address method is not recognized:
<div class="field">
<%= form.label :streetNumber %>
<%= form.text_field :organization.address.streetNumber%>
</div>
In controller, I have access to the address of the organization like:
#organization.address.streetNumber
PS: I'm new to Rails ;)
That's what fields_for is for.
<%= form_for #person do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for :permission, #person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<%= person_form.submit %>
<% end %>

How to post array of objects in rails?

I have the following code in my
new.html.erb
<%= form_tag puppies_path do %>
<% #kennel.each do |puppy| %>
<%= fields_for 'puppies[]', puppy do |p| %>
<div class="field">
<%= p.label :name %><br>
<%= p.text_field :name %>
</div>
<div class="field">
<%= p.label :breed %><br>
<%= p.text_field :breed %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= submit_tag %>
</div>
<% end %>
And puppies[] array variable, which is supposed to post array of objects to controller is posting only single object. Please help to post an array to controller. Thanks in advance!
The usual setup for fields_for is something like this.
<% #kennel.each do |kennel| %>
<%= fields_for :puppies, #kennel.puppies do |p| %>
Yes, I have just found an answer...
In new.html.erb file
<%= form_tag puppies_path do %>
<% 2.times do %>
<%= render 'puppies_group_form' %><br>
<% end %>
<%= submit_tag "Submit" %>
<% end %>
In _puppies_group_form
Name <%= text_field_tag "puppies[][name]" %>
Breed <%= text_field_tag "puppies[][breed]" %>

Rails - Couldn't find Student with 'id'=

I'm getting the error above when I try to create a a 'mark' for a 'student'. I can't figure out how to pass the :student_id when I create a new mark.
Routes
Rails.application.routes.draw do
resources :students do
resources :marks
end
resources :marks
root 'students#index'
Marks Controller
class MarksController < ApplicationController
def create
#student = Student.find(params[:student_id])
#mark = #student.marks.create(params[:input1, :input2, :input3, :weight1, :weight2, :weight3, :mark1, :mark2, :mark3, :final_mark].permit(:input1, :input2, :input3, :weight1, :weight2, :weight3, :mark1, :mark2, :mark3, :final_mark))
#mark.save
if #mark.save
redirect_to student_path(#student)
else
render 'new'
end
end
def new
#mark = Mark.new
end
private
def set_mark
#mark = Mark.find(params[:id])
end
end
Students Show View
<p id="notice"><%= notice %></p>
<p>
<strong>Student Number</strong>
<%= #student.StudentNumber %>
</p>
<p>
<strong>Project Title</strong>
<%= #student.ProjectTitle %>
</p>
<p>
<strong>Project PDF</strong>
<%= #student.ProjectTitle %>
</p>
<p>
<strong>Reader 1</strong>
<%= #student.Reader1 %>
</p>
<p>
<strong>Reader 2</strong>
<%= #student.Reader2 %>
</p>
<h3> <%= link_to 'Add Mark', new_student_mark_path(#student), class:"btn btn-warning"%> </h3>
<p>
<strong>Reader 3</strong>
<%= #student.Reader3 %>
</p>
<%= link_to 'Edit', edit_student_path(#student) %> |
<%= link_to 'Back', students_path %>
Marks Form
<%= form_for #mark, html: {multipart: true} do |f| %>
<% if #mark.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#mark.errors.count, "error") %> prohibited this grading from being saved:</h2>
<ul>
<% #mark.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label 'Introduction' %><br>
<%= f.text_area :input1 %>
<%= f.number_field :weight1 %>
<%= f.number_field :mark1 %>
</div>
<div class="field">
<%= f.label 'Main' %><br>
<%= f.text_area :input2 %>
<%= f.number_field :weight2 %>
<%= f.number_field :mark2 %>
</div>
<div class="field">
<%= f.label 'Conclusion' %><br>
<%= f.text_area :input3 %>
<%= f.number_field :weight3 %>
<%= f.number_field :mark3 %>
</div>
<div class="actions">
<%= f.submit class:"btn-xs btn-success"%>
</div>
<% end %>
Mark model
class Mark < ActiveRecord::Base
belongs_to :student
end
Student Model
class Student < ActiveRecord::Base
has_many :marks
has_attached_file :document
validates_attachment :document, :content_type => { :content_type => %w(application/pdf) }
end
It's probably something really stupid but if anyone could explain the problem I'd be really grateful.
Thanks
I don't suggest you using hidden fields for this purpose.
You should pass student together with mark into form_for helper and rails will generate proper url for you which will look like: /students/:student_id/marks
In this case it will be possible to extract student_id from params in your action later.
form_for [#student, #mark], html: {multipart: true} do |f|
More information about nested resources:
http://guides.rubyonrails.org/routing.html#nested-resources
http://www.informit.com/articles/article.aspx?p=1671632&seqNum=7
https://gist.github.com/jhjguxin/3074080
UPDATE:
Forgot to mention that in order to make this work you need to pass student instance into your template at new action:
def new
#student = Student.find(params[:student_id])
#mark = #student.marks.build
end

Form Refactoring Rails

I am currently creating a form in my rails application but would like some advice on refactoring it. The form is being used to save bagel toppings for an order. The user can select three different toppings (topping1, topping2, and topping3), and the form fields for each one are virtually identical.
ie.
<%= form_for order_item, remote: true do |f| %>
...
<div class="field">
<%= f.label :topping1 do %>
<%= image_tag("http://www.189harwood.com/statics/images/products/ingredients/butter.png", class:"topping") %>
Butter
<% end %>
<%= f.radio_button :topping1, "butter", checked: "checked" %>
</div>
<div class="field">
<%= f.label :topping1 do %>
<%= image_tag("http://www.wpclipart.com/food/dairy/cheese/soft_cream_cheese.png", class:"topping") %>
Cream Cheese
<% end %>
<%= f.radio_button :topping1, "cream cheese" %>
</div>
...
<div class="field">
<%= f.label :topping2 do %>
<%= image_tag("http://www.189harwood.com/statics/images/products/ingredients/butter.png", class:"topping") %>
Butter
<% end %>
<%= f.radio_button :topping2, "butter", checked: "checked" %>
</div>
<div class="field">
<%= f.label :topping2 do %>
<%= image_tag("http://www.wpclipart.com/food/dairy/cheese/soft_cream_cheese.png", class:"topping") %>
Cream Cheese
<% end %>
<%= f.radio_button :topping2, "cream cheese" %>
</div>
...
<%= f.submit "Wrap It Up" %>
<% end %>
Any suggestions on how I can refactor this? Thanks
Try storing the toppings in an array of hashes in your model:
def self.toppings
[{name:'butter', url:'http://www.189harwood.com/statics/images/products/ingredients/butter.png'}, {name:'cream cheese', url:'http://www.wpclipart.com/food/dairy/cheese/soft_cream_cheese.png'}, {...}]
end
In your controller:
my_action
#topping_options = Model.toppings
end
And in your view:
<div class="field">
<% #topping_options.each do |topping| %>
<%= f.label topping[:name].to_sym, topping[:name].humanize %>
<%= image_tag(topping[:url], class:"topping") %>
<%= f.radio_button topping[:name].to_sym %>
<% end %>
</div>

Rails 4 - Nested Object Won't Save

Note: I've read a couple posts similar to this. But non of the solutions answer my question
I have two objects, Bid and Moz. When I build my Bid object, everything seems to save okay, except for the Moz objects.
Model
class Bid < ActiveRecord::Base
belongs_to :user
has_many :mozs, :dependent => :destroy
accepts_nested_attributes_for :mozs, :allow_destroy => true
end
class Moz < ActiveRecord::Base
belongs_to :bid
end
Bids::Build Controllers
class Bids::BuildController < ApplicationController
include Wicked::Wizard
steps :intro, :problems, :solutions, :pricing
def show
#bid = Bid.find(params[:bid_id])
render_wizard
end
def update
#bid = Bid.find(params[:bid_id])
#bid.attributes = build_params
4.times { #bid.mozs.build } if step == steps.second
render_wizard #bid
end
def new
#bid = Bid.new
redirect_to wizard_path(steps.first, :bid_id => #bid.id)
end
def build_params
params.require(:bid).permit(:client_name, :intro, :prob1, :prob2, :prob3, :site_feel, :search_phrase, :page_score, :total_links,
:internal_links, :external_links, :competition, :complete, :user_id, :us_company, :philosophy_1,
:philosophy_2, :website_conclusions, :is_onsite_seo, :onsite_seo, :is_ongoing_seo, :ongoing_seo,
:is_ppc, :ppc, :is_social_media, :social_media, :is_google_places, :google_places, :is_adwords_express,
:adwords_express, moz_attributes: [:url, :id, :_destroy]
)
end
private
def finish_wizard_path
root_url
end
end
solutions.html.erb
<%= form_for (#bid), url: wizard_path do |f| %>
<% if #bid.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#bid.errors.count, "error") %> prohibited this bid from being saved:</h2>
<ul>
<% #bid.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% if #bid.is_onsite_seo? %>
<div class="field">
<%= f.label :onsite_seo %><br>
<%= f.text_area :onsite_seo %>
</div>
<% end %>
<% if #bid.is_ongoing_seo? %>
<div class="field">
<%= f.label :ongoing_seo %><br>
<%= f.text_area :onsite_seo %>
</div>
<% end %>
<div class="field">
<%= f.label :ppc %><br>
<%= f.text_area :ppc %>
</div>
<div class="field">
<%= f.label :social_media %><br>
<%= f.text_area :social_media %>
</div>
<div class="field">
<%= f.label :google_places %><br>
<%= f.text_area :google_places %>
</div>
<div class="field">
<%= f.label :adwords_express %><br>
<%= f.text_area :adwords_express %>
</div>
<%= f.fields_for :mozs do |builder| %>
<%= render partial: "moz_fields", locals: {f: builder} %>
<% end %>
<%= link_to_add_association "Add URL", f, :mozs %>
<div class="actions">
<%= f.submit %>
or <%= link_to "skip this step", next_wizard_path %>
</div>
<% end %>
_moz_fields.html.erb
<div class="field fields">
<%= f.label :url, "Comparative URL" %><br>
<%= f.text_field :url %>
<%= f.hidden_field :destroy %>
<%= link_to_function "remove", "remove_fields(this)"%>
</div>
I don't understand why they won't save. In addition, I noticed something odd -- when I don't use a partial for the nested object and use the f form builder for the #bid object (as opposed to 'builder'), I get an error no method or variable :url, but a Moz object is saved (although, not with any of the desired attributes).
My opinion that you misspelled with permit attrbibutes hash, try to change moz_attributes to mozs_attributes.
params.require(:bid).permit(..., :mozs_attributes: [:url, :id, :_destroy])
If you send the parameter _destroy: 1 through your hidden field
<%= f.hidden_field :destroy %>
you instruct Rails to destroy the child moz object, or in your case, prevent it from being created.
As for the second part of your question, if you inline the partial from this
<%= f.fields_for :mozs do |builder| %>
<%= render partial: "moz_fields", locals: {f: builder} %>
<% end %>
to this
<%= f.fields_for :mozs do |builder| %>
<div class="field fields">
<%= f.label :url, "Comparative URL" %><br>
<%= f.text_field :url %>
<%= link_to_function "remove", "remove_fields(this)"%>
</div>
<% end %>
it won't work, because the model object for the scope f is your #bid, not moz. Bids have no url attribute, hence the error.
With the input fields being created in the wrong form builder scope, you did not actually transmit any attributes for your moz object, and so it was created blank. As a side effect, this also meant not sending the _destroy parameter, so the object was saved.
Instead, inline the partial like this (I renamed builder to moz for clarity):
<%= f.fields_for :mozs do |moz| %>
<div class="field fields">
<%= moz.label :url, "Comparative URL" %><br>
<%= moz.text_field :url %>
<%= link_to_function "remove", "remove_fields(this)"%>
</div>
<% end %>

Resources