I'am trying to add some fields to my nested form. I've included the gem nested_forms (https://github.com/ryanb/nested_form).
For my prebuilt maps, it works fine, but i can't add new fields.
My controller:
def new
#people = Person.all
#vehicles = Vehicle.all
#roles = Role.all
#pratice_people = []
#people.each do |a|
if a.at1 == true
#pratice_people << a
end
end
#practice = Practice.new
#pratice_people.count.times { #practice.uebung_maps.build }
render action: "new"
end
and my form:
<% #runs = 0 %>
<%= f.fields_for :uebung_maps do |map| %>
<tr>
<%= map.hidden_field :role_id, :id => "role_id_#{#runs}" %>
<%= map.hidden_field :vehicle_id, :id => "vehicle_id_#{#runs}" %>
<%= map.hidden_field :person_id , :value => #pratice_people[#runs].id %><br/>
<td><%= #pratice_people[#runs].name %></td>
<td><%= map.select :role_id, options_from_collection_for_select(#roles, :id, :name), :include_blank => true %></td>
<td><%= map.select :vehicle_id, options_from_collection_for_select(#vehicles, :id, :name), :include_blank => true %></td>
<td><%= map.text_field :time %></td>
</tr>
<% #runs += 1 %>
<% end %>
<%= f.link_to_add "+" , :uebung_maps %>
If i try to access the page, i get following error report
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Do I have to (or how to) create a logic to rerun Practice.uebung_maps.build?, because I thought this is done within the nested_forms gem....
First, make sure the models are created correctly.
class Practice < ActiveRecord::Base
has_many :uebung_maps
accepts_nested_attributes_for :uebung_maps
end
class UebungMap < ActiveRecord::Base
end
Second, make sure the form_for is nested correctly
<%= nested_form_for #practice do |f| %>
<%= f.fields_for :uebung_maps do |uebung_maps_form| %>
<%= uebung_maps_form.text_field :time %>
<% end %>
<p><%= f.link_to_add "+", :uebung_maps %></p>
<% end %>
Related
I followed this railscast.
Controller: project_sub_types_controller.rb
def new
#svn_repos = ['svn_software','svn_hardware']
#project_sub_type = ProjectSubType.new
#project_sub_type.repositories.build
end
def edit
#svn_repos = ['svn_software','svn_hardware']
#project_sub_type = ProjectSubType.find(params[:id])
end
Model: project_sub_type.rb
class ProjectSubType < ActiveRecord::Base
belongs_to :project_type
has_many :repositories, :dependent => :destroy
def repositories_attributes=(repos_attributes)
repos_attributes.each do |attributes|
repositories.build(attributes)
end
end
end
View: _form.html.erb
<%= form_for #project_sub_type, :html => {:class => 'project_subtype_form'} do |f| %>
<%= f.label :name, "Project sub type name" %>
<%= f.text_field :name %>
<% for repos in #project_sub_type.repositories %>
<%= fields_for "project_sub_type[repositories_attributes][]", repos do |repos_form| %>
<% #svn_repos.each do |repos| %>
<%= repos_form.check_box :repos_name, {}, "#{repos}", nil %>
<%= h repos -%>
<% end %>
<% end %>
<% end %>
<%= f.submit "Save"%>
This works perfectly during creation of a new record. But Y does the fields_for duplicates during edit. During create I see 2 checkboxes but during edit there are 4 checkboxes which duplicates the other 2 checkboxes. What am I doing wrong?
Update : The more times I click on edit and the duplication increases by 1.
<% for repos in #project_sub_type.repositories %>
<%= fields_for "project_sub_type[repositories_attributes][]", repos do |repos_form| %>
<% #svn_repos.each do |repos| %>
<%= repos_form.check_box :repos_name, {}, "#{repos}", nil %>
<%= h repos -%>
<% end %>
<% end %>
<% end %>
Get rid of that and do:
<%= f.fields_for :repositories do |repo_form| %>
<% #svn_repos.each do |rep| %>
<%= repo_form.check_box :repos_name, {}, rep, nil %>
<%= h rep -%>
<% end %>
<% end %>
Also get rid of repositories_attributes= method in your model and add accepts_nested_attributes_for :repositories
The railscast you linked is 7 years old. :)
I have created an simple rails project. All worked fine until I tried to add a new model Paintings that belongs_to treatment and an Patient that has_many Paintings through Treatment. So somehow the nested form I created does not show up, I believe it has to do with the controller! Thanks, and greetings from Germany!
Treatments controller:
class TreatmentsController < ApplicationController
def create
#patient = Patient.find(params[:patient_id])
#treatment = #patient.treatments.create(params[:treatment])
redirect_to patient_path(#patient)
end
def destroy
#patient = Patient.find(params[:patient_id])
#treatment = #patient.treatments.find(params[:id])
#treatment.destroy
redirect_to patient_path(#patient)
end
end
And the form for treatments with nested fields_for that doesn't show up:
<%= form_for([#patient, #patient.treatments.build]) do |f| %>
<div class="field">
<%= f.label :content %>
<%= f.text_area :content, :cols => "30", :rows => "10" %>
</div>
<div class="field">
<%= f.label :category_id %>
<%= f.collection_select :category_id, Category.find(:all), :id, :typ %>
</div>
<%= f.fields_for :paintings do |ff| %>
<div class="field">
<%= ff.label :name, 'Tag:' %>
<%= ff.text_field :name %>
</div>
<% end %>
<div class="field">
<%= f.submit nil, :class => 'btn btn-small btn-primary' %>
</div>
<% end %>
UPDATE:
Show Site:
<% #patient.treatments.each do |treatment| %>
<tr>
<td><%= treatment.category.try(:typ) %></td>
<td><%= treatment.content %></td>
<td><%= treatment.day %></td>
<td><div class="arrow"></div></td>
</tr>
<tr>
Please try
= f.fields_for :paintings, Painting.new do |p|
Even the question is quite old, but you are missing the new that is crucial to this question. The methods destroy and create doesn't have anything with this issue. If you have a new method, which looks something like this:
class TreatmentsController < ApplicationController
def new
#patient = Patient.new
end
end
Then the solution would be do modify the new method to "build" the paintings like this:
class TreatmentsController < ApplicationController
def new
#patient = Patient.new
#patient.paintings.build
end
end
Try doing following in new action in controller
#patient.treatments.build
Check out build_association part http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to
You should also read about nested attributes.
Use those for reference
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Dumb error, but I was using:
<% f.fields_for :partner do |fp| %>
instead of:
<%= f.fields_for :partner do |fp| %>
is case you have an association where it is optional:
in the controller:
#associated_model = #model.associated_model || #model.build_associated_model
in the view:
<%= form.fields_for :associated_model do |am| %>
Ok this is driving me round the bend. I have three models [which are relevant to this quesiton]: Outfit, Outfit_relationship and Answer. Outfit is the parent model and the others are the childs. The Outfit model looks like this:
class Outfit < ActiveRecord::Base
attr_accessible :user_id, :outfit_origin_id, :outfit_parent_id, :outfitrelationship_id #review before going live
attr_accessible :item_id, :image_size_height, :image_size_width, :image_x_coord, :image_y_coord, :zindex, :outfit_id
attr_accessible :description, :question_id, :user_id, :outfit_id
has_many :answers
has_many :outfit_relationships
accepts_nested_attributes_for :outfit_relationships, :allow_destroy => :true
accepts_nested_attributes_for :answers
Note that the 2nd and 3rd attr_accessible are to access the attributes from the other models. I'm not sure this is absolutely necessary, some articles say it is, some say it isn't, so I put it in.
I've created a multi-model form for this data which I want to publish with one button. Here is the code:
<%= form_for(#outfit) do |post_outfit| %>
<%= post_outfit.fields_for #outfit.outfit_relationships do |build| %>
<table>
<tr>
<td>X Coord <%= build.text_area :image_x_coord, :size => '1x1' %></td>
<td>Y Coord <%= build.text_area :image_y_coord, :size => '1x1' %></td>
<td>Z Index <%= build.text_area :zindex, :size => '1x1' %></td>
<td>Height <%= build.text_area :image_size_height, :size => '1x1' %></td>
<td>Weight <%= build.text_area :image_size_width, :size => '1x1' %></td>
</tr>
</table>
<% end %>
<%= post_outfit.fields_for #outfit.answers do |build| %></br></br>
<%= image_tag current_user.fbprofileimage, :size => "40x40" %></br>
<%= current_user.name %></br>
Comment: <%= build.text_area :description, :size => '10x10' %>
<% end %>
<%= post_outfit.fields_for #outfit do |build| %> </br>
origin id: <%= build.text_area :outfit_origin_id, :size => '1x1' %></br>
parent id: <%= build.text_area :outfit_parent_id, :size => '1x1' %></br>
<% end %>
<div id="ss_QID_actions_container">
<%= post_outfit.submit "Submit checked", :class => "btn btn-small btn-primary" %>
</div>
<% end %>
And here are the relevant buts of the outfit controller:
def new
#outfit = Outfit.new
#outfit.save
#outfit.answers.build
#outfit.outfit_relationships.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: #outfit }
end
end
def create
#outfit = Outfit.new(params[:id])
#comment = #outfit.answers.create(params[:answer])
#outfitrelationship = #outfit.outfit_relationships.create(params[:outfit_relationship])
redirect_to outfit_path(#outfit)
So the problem is nothing gets written into my database apart from the IDs. I'm sure I'm dong something stupid here, but can't figure out why.
Alright I made a custom page in Active Admin called "Newest Rooms" and it shows a table with the Hotel Rooms of the current date.
Now I want to add a form the this custom page where I can pick the Date. I've managed to make the form appear with the Datepicker through:
<%= semantic_form_for :newest_rooms, :builder => ActiveAdmin::FormBuilder do |f|
f.inputs do
f.input :Datum, :as => :datepicker
end
f.buttons
end %>
But no idea how to send this to the right controller and to the method HotelRoom.newest_rooms
I hope someone can explain to me how to do this. I've added the code below:
newest_room.rb
ActiveAdmin.register_page "Newest Rooms" do
menu :label => "Newest Rooms"
content do
render "newest_rooms"
end
end
_newest_room.html.erb
<% #cities = Hotel.cities %>
<%= semantic_form_for :newest_rooms, :builder => ActiveAdmin::FormBuilder do |f|
f.inputs do
f.input :Datum, :as => :datepicker
end
f.buttons
end %>
<ul class="room_list">
<% #cities.each do |c| %>
<li>
<table>
<tr>
<td>
<h2><%= c.City %></h2>
</td>
</tr>
<tr class="room_column">
<td>Hotel</td>
<td>Free Rooms</td>
<td>BN-Price</td>
<td>Old Price</td>
</tr>
<% #rooms = HotelRoom.newest_rooms(c.City) %>
<% #rooms.each do |r| %>
<tr>
<td><%= r.hotel.Hotelname %></td>
<td><%= r.FreeRooms %></td>
<td><b><%= r.Price %>€</b></td>
<td><%= r.OldPrice %>€</td>
</tr>
<%end%>
</table>
</li>
<% end %>
</ul>
hotel_room.rb
class HotelRoom < ActiveRecord::Base
validates :title, :presence => true
self.table_name = "hotel_room"
belongs_to :hotel, :foreign_key => 'H_ID'
accepts_nested_attributes_for :hotel
def to_key
[self.ID]
end
def self.newest_rooms(city)
HotelRoom.find(:all, :joins => :hotel, :conditions => ["hotel.City = ? and hotel_room.Date = ?", city, Date.today])
end
end
add an url to your semantic form, like...
<%= semantic_form_for :newest_rooms, :url => hotel_newest_room_path, :builder => ActiveAdmin::FormBuilder do |f| %>
I have a model:
class Contact < ActiveRecord::Base
has_many :phones
accepts_nested_attributes_for :phones
end
I want to build 50 phone #s that users can add (there may already be phones 1 or 5, but I always want 50 available)
In my controller:
while contact.phones.length < 50
contact.phones.build({:phone_type_id => PhoneType['a_cool_type'].id})
end
In my view, I want to have 2 columns of phone #s 25 rows each
<%= semantic_form_for contact do |form| %>
<table width=50%>
<%= form.inputs :for => :phones[0..25] do |phone_form| %>
<td align="center"><%= phone_form.input :number, :label => false %></td>
....
<% end %>
</table>
<table width=50%>
<%= form.inputs :for => :phones[25..49] do |phone_form| %>
<td align="center"><%= phone_form.input :number, :label => false %></td>
....
<% end %>
</table>
<%end %>
Obviously the line:
<%= form.inputs :for => :phones[25..49] do |phone_form| %>
doesn't work, but it conveys my intention ( I hope). I want to have more control over how formtastic grabs the underlying object association.
The following works, but I can't do two columns easily without fancy css.
<%= form.inputs :for => :phones do |phone_form| %>
Any suggestions?
---------- Update ----
I was able to get around this in a roundabout way:
I built up a separate list of phone #s not as contact.phones.build, but Phone.new(:contact_id => contact.id) and store those in a list called #new_phones
Then my form looks like this:
<%= semantic_form_for #contact, :url => ..., do |f| %>
<% #new_phones[0...25].each_with_index do |phone, i| %>
<%= f.fields_for :phones, phone, :child_index => i do |phone_form| %>
<%= render "phone_fields", {:phone_form => phone_form, :phone => phone} %>
<%end%>
<% end %>
....
<% #new_phones[25...50].each_with_index do |phone, i| %>
<%= f.fields_for :phones, phone, :child_index => i+25 do |phone_form| %>
<%= render "phone_fields", {:phone_form => phone_form, :phone => phone} %>
<%end%>
<% end %>
<%end%>
This allowed me to display 25 phones on one part of the page, and 25 on another, with nested_attributes_for :phones working as expected on form submit.
I've always had problems with getting nested attributes working as I want but this may help resolve your issue.
Model:
class Contact < ActiveRecord::Base
has_many :phones
accepts_nested_attributes_for :phones
end
Controller:
See we're looping #contract.phones.build 50 times, this creates 50 new instances.
class Contact < ApplicationController
def new
#contact = Contact.new
25.times do
#contact.phones.build
end
end
end
View new.html.erb :
...
<%= p.semantic_fields_for :phones do |ec| %>
<%= ec.input :number %>
<% end %>
...
I did try a few attempts to intercept the loop, sadly with no definite clean avail.