I'm new to both programming and Ruby on Rails. I'm just trying with a sample 2 level deep nesting. When I followed Ryan's Scraps (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes) for 1 level deep nesting everything well and good but when I extended for 2 level deep with following requirement:
Instead of creating parent, children and grandchildren at a time I want to create parent first then child and grandchild together.My code is
My model:
class Parent < ActiveRecord::Base
has_many :children
has_many :grand_children
accepts_nested_attributes_for :children, :allow_destroy => true
accepts_nested_attributes_for :grand_children, :allow_destroy => true
end
class Child < ActiveRecord::Base
belongs_to :parent
has_many :grand_children
accepts_nested_attributes_for :grand_children
end
class GrandChild < ActiveRecord::Base
belongs_to :parent
belongs_to :child
end
My children controller -new method:
def new
#parent = Parent.find(params[:parent_id])
child = Child.new
child.grand_children.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #child }
end
end
My children _form template is
<%= form_for([#parent, #parent.children.build]) do |form| %>
<div>
<%= form.label :name %><br />
<%= form.text_field :name %>
</div>
<div class="field">
<%= form.label :sex %><br />
<%= form.text_field :sex %>
</div>
<div>
<%= form.fields_for :grand_children do |grand_child_form| %>
<%= render :partial => "grand_children/form", :locals => { :form => grand_child_form} %>
<% end %>
</div>
<% end %>
Here I'm not getting any error as such but when I select new child the grand_child is not appearing,
<%= form.fields_for :grand_children do |grand_child_form| %>
<%= render :partial => "grand_children/form", :locals => { :form => grand_child_form} %>
<% end %>
is not getting reflected at all .
Thanks in advance
Hey folks I got d solution by trial and error,
form template for children is
<div>
<%= form.fields_for :grandchildren, #grand_child do |grand_child_form| %>
<%= render :partial => "grandchildren/form", :locals => { :form => grand_child_form} %>
<% end %>
</div>
Related
Nesting forms always seems to mangle my brain. Any help would be appreciated.
I want to make a booking form for a course. The course has start dates associated with it. I want the form to update the course start dates once the course is selected from the dropdown selection in the form. I have this much done. I've added cocoon gem and have the forms all set up but I cannot seem to get the form to generate a list based on the course selected in the form.
Models:
class Booking < ApplicationRecord
belongs_to :course
belongs_to :user
end
class Course < ApplicationRecord
has_many :bookings
has_many :schedules
accepts_nested_attributes_for :schedules, :reject_if => :all_blank, :allow_destroy => true
end
class Schedule < ApplicationRecord
belongs_to :course
end
Form Views
Booking Form
<%= simple_form_for(#booking) do |f| %>
<%= f.error_notification %>
<div class="ice-card">
<!-- <div class="form-inputs">-->
<%= f.input :user_id, :input_html => { :value => current_user.id} %>
<%= f.input :user_email, :input_html => { :value => current_user.email}, label: "Contact Email" %>
<%= f.association :course, label_method: :header, :input_html => { :selected => :course }, :include_blank => false, label: "Course Name" %>
<%= f.simple_fields_for :schedules do |schedule| %>
<%= render 'schedule_fields', :f => schedule %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit, class: "btn btn-primary" %>
</div>
<% end %>
Schedule Form partial
<%= f.input :start_date, as: :date %>
I have the following code form my passport_visas.rb model
ActiveAdmin.register PassportVisa do
menu :label => "Visas"
form :partial => "form"
index :title => "Visas"
end
And this is my code for the partial "form"
<%= semantic_form_for [:admin, #passport_visa] do |f| %>
<%= f.inputs "Main information" do %>
<%= f.input :country %>
<%= f.input :citizenship, :as => :radio, :collection => {"US Citizen" => 0, "Foreign National" => 1} %>
<%= f.input :visa_type, :as => :select, :collection => ["Tourist", "Business", "Official"] %>
<%= f.input :visa_required, :label => "Is Visa Required?", :as => :radio, :collection => {"Required" => 0, "Not Required" => 1} %>
<%= f.input :maximum_stay, :label => "Maximum Stay" %>
<% end %>
<fieldset class="actions">
<ol>
<li class="action input_action" id="passport_visa_add_new_entry">
<input name="new_entry" type="button" value="Add New Entry">
</li>
<li class="action input_action" id="passport_visa_remove_entry">
<input name="remove_entry" type="button" value="Remove Entry">
</li>
</ol>
</fieldset>
<!-- Problem -->
<%= f.inputs "Entries" do %>
<%= f.has_many :visa_entries do |entry| %>
<%= entry.input :type_of_entry, :as => :select, :collection => ["Testing"] %>
<% end %>
<% end %>
<%= f.actions %>
<% end %>
And I'm getting this error message: "undefined method `has_many' for #Formtastic::FormBuilder:0x10c234c38"
I'm trying the entire day to setup this form, here's my model's code:
passport_visa.rb
class PassportVisa < ActiveRecord::Base
has_many :visa_entries
accepts_nested_attributes_for :visa_entries
end
visa_entry.rb
class VisaEntry < ActiveRecord::Base
belongs_to :passport_visa
attr_accessible :type_of_entry, :maximum_validity, :embassy_fees, :service_fees, :processing_time
end
Finally I found a work around for that. So here's what I did to make it work:
First I got rid of the _form partial, because for some reason the "has_many" don't work inside there.
I modified my 2 models:
passport_visa.rb
class PassportVisa < ActiveRecord::Base
has_many :visa_entries
accepts_nested_attributes_for :visa_entries
attr_accessible :visa_entries_attributes, :country, :citizenship, :visa_type, :visa_required, :maximum_stay
validates_presence_of :country, :citizenship, :visa_type, :visa_required, :maximum_stay
end
visa_entry.rb
class VisaEntry < ActiveRecord::Base
belongs_to :passport_visa
attr_accessible :type_of_entry
validates_presence_of :type_of_entry
end
And the last part, the actual form:
form do |f|
f.inputs "Entries" do
f.has_many :visa_entries do |ff|
ff.input :type_of_entry, :as => :select, :collection => ["Testing"]
end
end
f.actions
end
Bye!
I am trying to get a Project form to build the first (starting) time of several (up to 12) volunteer time blocks.
project.rb
class Project < ActiveRecord::Base
attr_accessible :title, ...
has_many :vol_times, :dependent => destroy
accepts_nested_attributes_for :vol_times, :reject_if => lambda { |a| a[:start_time].blank? }, :allow_destroy => true
...
end
vol_time.rb
class Vol_time < ActiveRecord::Base
attr_accessible :start_time, ...
belongs_to :project
end
ProjectsController
class ProjectsController < ApplicationController
before_filter :signed_in_user, only: :create
...
def new
#project = Project.new
#user = current_user
#project.vol_times.build
end
...
end
Vol_Times Controller
class Vol_TimesController < ApplicationController
def new
#reward = Reward.new
end
...
end
My view looks like this...
<%= form_for(#project) do |f| %>
<div class="form_field_block">
<p class="form_label"> Project Title</p>
<%= f.text_field :title, :size => 40, :placeholder => " Project Title...", :class => "frm" %>
</div>
<div class="form_field_block">
<p class="form_label"> Project Sub-title</p>
<%= f.text_field :sub_title, :size => 40, :placeholder => " Project Sub-title...", :class => "frm" %>
</div>
<p class="clearing"></p>
<div class="form_field_block">
<% f.fields_for :vol_times do |builder| %>
<%= render :partial => 'start_time', :f => builder %>
<% end %>
</div>
<p class="clearing"></p>
<%= button_tag "btn_start_project.png", :class => "btn_save" %>
<% end %>
And the _partial looks like this...
<%= f.label :start_time, "Starting Time" %>
<%= f.text_field :start_time %>
When I view the page, I see the containing <div>, but not the contents of the ERB, which should be parsed from the _partial.
Any ideas why this isn't working? I got the general context from Ryan Bates' RailsCast #196 - Here
you are missing a = on the fields_for. It should be
<%= f.fields_for :vol_times do |builder| %>
I am working on building a blog with categorization. I am a bit stuck on how to implement categorization in the form. I have setup a has many through relationship and want to add check boxes to associate a blog with multiple categories. What I have so far is passing the categories through to the view, and I can list them out, however I cannot get the form_for method working for some reason.
Here is my code.
blog model
class Blog < ActiveRecord::Base
attr_accessible :body, :title, :image
has_many :categorizations
has_many :categories, through: :categorizations
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates :title, :body, :presence => true
end
Category Model
class Category < ActiveRecord::Base
has_many :categorizations
has_many :blogs, through: :categorizations
attr_accessible :name
end
Categorization Model
class Categorization < ActiveRecord::Base
attr_accessible :blog_id, :category_id
belongs_to :blog
belongs_to :category
end
Blog new controller
def new
#blog = Blog.new
#categories = Category.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: #blog }
end
end
Blog new form view
<%= form_for(#blog, :url => blogs_path, :html => { :multipart => true }) do |f| %>
<% if #blog.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#blog.errors.count, "error") %> prohibited this blog from being saved:</h2>
<ul>
<% #blog.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.file_field :image %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="field">
Categories:
<% #categories.each do |category| %>
<% fields_for "blog[cat_attributes][]", category do |cat_form| %>
<p>
<%= cat_form.check_box :name %>
</p>
<% end %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This code is my failing point
<% #categories.each do |category| %>
<% fields_for "blog[cat_attributes][]", category do |cat_form| %>
<p>
<%= cat_form.check_box :name %>
</p>
<% end %>
<% end %>
Although I am not positive I am approaching any of it right since I am currently learning. Any advice on how to accomplish this.
Thanks,
CG
First of all, you probably don't need a separate Categorization model unless there's a use case you haven't described here. You can set up a many-to-many relationship like this:
class Blog < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :blogs
end
You should have a database table like this:
class CreateBlogsCategories < ActiveRecord::Migration
def change
create_table :blogs_categories, id: false do |t|
t.references :blog
t.references :category
end
end
end
Then you can construct the view like this:
<div class="field">
Categories:
<% #categories.each do |category| %>
<%= label_tag do %>
<%= check_box_tag 'blog[category_ids][]', category.id, #blog.category_ids.include?(category.id) %>
<%= category.name %>
<% end %>
<% end %>
</div>
Lastly, in your form_for, you specify url: blogs_path - you should remove this if you plan to use this form for the edit action as well, because that should generate a PUT request to /blogs/:id. Assuming you used resources :blogs in routes.rb, Rails will determine the correct path for you based on the action used to render the form.
I'm
I'm building a website on Ruby On Rails 3.0.7 and I want to save a store object and its languages. So, I have the following models:
class Store < ActiveRecord::Base
belongs_to :user
has_many :languages, :through => :store_languages
has_many :store_languages
accepts_nested_attributes_for :store_languages
#Validations
validates :title, :presence => true, :length => 5..100
validates :contact_email, :presence => true, :format => { :with => /^([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
end
class Language < ActiveRecord::Base
has_many :stores, :through => :store_languages
has_many :store_languages
end
class StoreLanguage < ActiveRecord::Base
belongs_to :store
belongs_to :language
validates :store_id, :presence => true
validates :language_id, :presence => true
end
StoresController's relevant actions:
def new
#store = Store.new
#store.store_languages.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #store }
end
end
# POST /stores
# POST /stores.xml
def create
#raise params.inspect
#store = current_user.stores.new(params[:store])
respond_to do |format|
if #store.save
format.html { redirect_to(#store, :notice => 'Store was successfully created.') }
format.xml { render :xml => #store, :status => :created, :location => #store }
else
#store.store_languages.build
format.html { render :action => "new" }
format.xml { render :xml => #store.errors, :status => :unprocessable_entity }
end
end
end
View: /stores/new.html.erb:
<%= form_for(#store) do |f| %>
<% if #store.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#store.errors.count, "error") %> prohibited this store from being saved:</h2>
<ul>
<% #store.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="title">Title*</label><br />
<%= f.text_field :title %>
</p>
<p>
<label for="description">Description</label><br />
<%= f.text_field :description %>
</p>
<p>
<label for="contact_email">Contact E-mail*</label><br />
<%= f.text_field :contact_email %>
</p>
<p>
<label for="logo">Logo</label><br />
<%= f.file_field :logo %>
</p>
<% f.fields_for :store_languages do |lf| %>
<%= lf.collection_select :language_id, #languages, :id, :name, {}, {:multiple => true } %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So, I've got the following records in the languages table:
id | name
3 English
4 EspaƱol
What happens is that when I create a new store selecting the two languages from the list, it will save the following at the store_languages table:
id | store_id | language_id
4 4 1
And the language_id = 1 doesn't exist.
If I debug the application at the create action, I get the following:
"store"=>{"title"=>"asdasdsdsadasdasdasd", "description"=>"", "contact_email"=>"asdasdsa#asdasdsad.com", "logo"=>"", "store_languages_attributes"=>{"0"=>{"language_id"=>["3", "4"]}}}
You can see that the ids are correct here: 3 and 4. So, I don't know why it saves 1.
Any ideas?
Try
<%= lf.collection_select :language_ids, #languages, :id, :name, {}, {:multiple => true } %>
(ie using ids instead of id in the attribute name)