Creating forms for Multiple Nested Resources in Rails 3 - ruby-on-rails

I have been following Ryan Bates' tutorial on nested forms Railscast 196
The form for the new action shows the nested attributes for quizzes but does not show nested attributes for the key. I am guessing this is because quizzes have a has_many relationship where key has a has_one relationship... But I cannot figure out what I'm doing wrong?
Any help is much appreciated!
This is my model:
class Repository < ActiveRecord::Base
has_many :quizzes, :dependent => :destroy
has_one :key, :dependent => :destroy
accepts_nested_attributes_for :key, :quizzes
end
This is my controller:
def new
#repository = Repository.new
3.times { #repository.quizzes.build }
#repository.key = Key.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #repository }
end
end
This is my view:
<div class="field">
<%= f.label :wp_uid %><br />
<%= f.text_field :wp_uid %>
<% f.fields_for :quizzes do |quiz_fields| %>
<p>
<%= quiz_fields.label :name, "Name" %><br />
<%= quiz_fields.text_field :name %>
</p>
<% end %>
<% f.fields_for :key do |key_fields| %>
<div class="field">
<%= key_fields.label :value, "Value" %><br />
<%= key_fields.text_field :value %>
</div>
<div class="field">
<%= key_fields.label :expiry, "Expiry" %><br />
<%= key_fields.date_select :expiry %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

You should try modifying your fields_for blocks to use <%= %>
Try changing to:
<%= f.fields_for :key do |key_fields| %>
The railscast could have been made before the change in Rails 3 to use <%= %> instead of <%%>.
Ryan has a nested_form gem that you may find useful for this as well. I haven't tried using it yet, but plan to next time I start a new project.
https://github.com/ryanb/nested_form

Try building the key object as
#reposity.build_key
From the rails docmentation
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Unsaved+objects+and+associations
If you wish to assign an object to a has_one association without saving it, use the build_association method. The object being replaced will still be saved to update its foreign key.

Related

How can I render a _form file from a different controller without having conflicting form_for's?

Let's say I have 2 models, Box.rb and Toy.rb. Rails gives me pages and methods to create new toys and boxes independently. However, I would like to ensure/provide the ability to create a box's first toy when creating a box for the first time.
In line with DRY, I wanted to simply put <%= render "Toy/form" %> inside the _form.html.erb file that is made for Box.
The problem is that Toy's _form file contains, well, a form_for method for obvious reasons. It's a problem for what I am trying to do because I will end up with 1 form nested in the other, while all I really want is to get the Toy fields while keeping to DRY…?
You should be using accepts_nested_attributes_for along with fields_for.Assuming your associations are like this
#box.rb
Class Box < ActiveRecord::Base
has_many :toys
accepts_nested_attributes_for :toys
end
#toy.rb
Class Toy < ActiveRecord::Base
belongs_to :box
end
#box_controller.rb
def new
#box = Box.new
#toy = #box.toys.build
end
def create
#box = Box.new(box_params)
if #box.save
-----
else
-----
end
end
private
def box_params
params.require(:box).permit(:box_attribute_1,:box_attribute_2,:more_box_attributes, toys_attributes: [:toy_attribute_1,:more_toy_attributes])
end
In your box/form,you can do like this
<%= form_for(#box) do |f| %>
<div class="field">
<%= f.label :box_attribute_1 %><br />
<%= f.text_field :box_attribute_1 %>
</div>
<div class="field">
<%= f.label :box_attribute_2 %><br />
<%= f.text_field :box_attribute_2 %>
</div>
<div class="field">
<%= f.label :box_attribute_3 %><br />
<%= f.text_field :box_attribute_3 %>
</div>
<%= f.fields_for #toy do |builder| %>
<%= render 'toys/form', :f => builder %>
<% end %>
<% end %>

rails getting value from view to conroller

Having an issue getting a value from a form to the controller. I am using rails 4.0.
My view looks like this (new.html.erb)
<h1> POST A NEW LISTING </h>
<% if current_user.nil? %>
<h2>You must be logged in to view this page </h2>
<% else %>
<%= form_for [#user, #listing] do |f| %>
<%= f.label :title, 'Title' %> <br />
<%= f.text_field :title %>
<%= f.label :general_info, 'General Information' %> <br />
<%= f.text_area :general_info %>
<%= f.label :included, 'Included' %> <br />
<%= f.text_field :included %>
<%= f.label :length, 'Length' %> <br />
<%= f.text_field :length %>
<%= f.label :price, 'Price' %> <br />
<%= f.text_field :price %>
<%= fields_for #tagging do |u| %>
<%= u.label :tag, 'Tag' %> <br />
<%= u.text_field :tag %>
<% end %>
<%= f.submit "submit" %>
<% end %>
<% end %>
I am trying to add tags. I have 2 models to handle the tags:
models -> tag.rb
class Tag < ActiveRecord::Base
has_many :taggings
has_many :listings, through: :taggings
end
models -> tagging.rb
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :listing
end
tags keep track of the tag names themselves, while taggings keeps track of the connection to the listings.
When a user submits the form they will type in a string tag such as: "exampletag". I then need to search my tag model to get the tag_id of that specific tag. If it exists I need to put the tag_id and listing_id into taggings. Currently I have the listing_id correct, but I am having a problem even accessing the :tag symbol from the form.
This is what I have so far. Not that currently :tag_id is hardcoded in because I cant get #current_tag to return the information I need.
listings_conroller.rb #create
def create
#user = User.find(current_user.id)
#listing = #user.listings.build(listing_params)
#save before we get the listing ID
if #listing.save
#current_tag = Tag.where(:name => params[:tag])
#taggings = Tagging.new(:tag_id => 1, :listing_id => #listing.id)
if #taggings.save
flash[:success] = "Success"
redirect_to root_path
else
render :action => 'new'
end
else
render :action => 'new'
end
end
I thought that #current_tag = Tag.where(:name => params[:tag]) would return the correct listing but it seems to be returning null when I submit the form with a name which is in the database.
got it!
Since tags is nested under taggings I needed to access the param as:
params[:tagging][:tag]
instead of params[:tag]

Ruby on Rails, two models in one form

I have two very similar models Pretreatment and Diagnosis, that belong to the model Patient:
class Pretreatment < ActiveRecord::Base
belongs_to :patient
attr_accessible :content
end
class Diagnosis < ActiveRecord::Base
belongs_to :patient
attr_accessible :content
end
class Patient < ActiveRecord::Base
attr_accessible :age, :name, :city, :street, :number
has_many :anamneses
has_many :befunds
end
On the Patient show page I'm displaying two forms, one for the Preatreatment and another for the Diagnosis:
<%= form_for([#patient, #patient.preatreatments.build]) do |f| %>
<div class="field">
<%= f.label :conten %><br />
<%= f.text_field :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= form_for([#patient, #patient.diagnosiss.build]) do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
My question is how can I bring the two forms together, so that the user only has to press once the submit button? Im not sure but I think nested attributes is not the right thing to handle it, maybe thefields_for` tag?
Update I tried to use fields_for tag:
<%= form_for([#patient, #patient.pretreatment.build]) do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<%= fields_for([#patient, #patient.diagnosiss.build]) do |u| %>
<div class="field">
<%= u.label :content %><br />
<%= u.text_field :content %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
But I get the error:
undefined method `model_name' for Array:Class in <%= fields_for([#patient,#patient.befunds.build]) do |u| %>
Use fields_for for the associated models.
There should be no square brackets arround the parameters of fields_for
In your code example, I cannot find the relation between Patient and Diagnosis, and the plural of diagnosis is diagnoses, you can specify this in config/initializers/inflections.rb:
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'diagnosis','diagnoses'
end
So your Patient model should contain
class Patient < ActiveRecord::Base
attr_accessible :age, :name, :city, :street, :number
has_many :diagnoses
end
And you can write in your form:
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<%= fields_for(#patient, #patient.diagnoses.build) do |u| %>
<div class="field">
<%= u.label :content %><br />
<%= u.text_field :content %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
You can achieve that using nested attributes :
patient.rb
class Patient < ActiveRecord::Base
attr_accessible :age, :name, :pretreatments_attributes, :diagnosiss_attributes
has_many :pretreatments
has_many :diagnosiss
accepts_nested_attributes_for :pretreatments
accepts_nested_attributes_for :diagnosiss
end
patients_controller.rb
def show
#patient = Patient.find(params[:id])
#patient.pretreatments.build
#patient.diagnosiss.build
respond_to do |format|
format.html # show.html.erb
format.json { render json: #patient }
end
end
patients/show.html.erb:
<%= form_for #patient do |f|%>
<h3>Pretreatments:</h3>
<%= f.fields_for :pretreatments do |field| %>
<%= field.label "Content" %></div>
<%= field.text_field :content %>
<% end %>
<h3>Diagnosis:</h3>
<%= f.fields_for :diagnosiss do |field| %>
<%= field.label "Content" %></div>
<%= field.text_field :content %>
<% end %>
<%=f.submit %>
<% end %>
And that all
There are a few ways of doing this:
The way the fields_for works is you have a form_for for the parent model and within it you can place fields_for the models which belong to the parent. A good example is given in the Rails Docs
A simple and more extensible option over time but not very "semantic" one would be to use JavaScript/JQuery. You could trigger $("form #new_pretreatments").submit(); and the same for the Diagnosis once a button is clicked.
Maybe instead you could have just one model to store them both. For example a model called Disease. Each time a patient gets a disease a new one is created and it has columns for each the Diagnosis and Pretreatment. It's probably the best option instead of adding another model for each bit of info a patient can have.
You can use fields_for for the second model, which works like form_for but doesn't generate the form tags. See the docs.
There are some gems available for nested forms. one of them is awesome_nested_fields. I haven't used this earlier but that shows good code in documentation. Another one is simple_form.
Hope that helps!!!

Using pre-existing records to add a new record to the database in rails

Okay so you can see my models and controller below. What I want to be able to do is when a user is adding a new lease, the user can select from a list of the properties already in the database for the property_id, and also select from a list of the tenants on file for the tenant_id. I am relatively new to rails and really don't have a clue how I would go about doing this. In my controller I put #property = Property.all #tenant = Tenant.all to make them accessible but I don't know how to leverage them in the way that I want.
Lease Model
class Lease < ActiveRecord::Base
attr_accessible :lease_end, :lease_start, :property_id, :tenant_id
belongs_to :tenant
belongs_to :property
end
Property Model
class Property < ActiveRecord::Base
attr_accessible :address_line_1, :city, :county, :image, :rent
belongs_to :lease
end
Tenant Model
class Tenant < ActiveRecord::Base
attr_accessible :email, :name, :phone
belongs_to :lease
end
Lease controller methods for adding a new lease and editing a lease
def new
#lease = Lease.new
#property = Property.all
#tenant = Tenant.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: #lease }
end
end
# GET /leases/1/edit
def edit
#lease = Lease.find(params[:id])
#property = Property.all
#tenant = Tenant.all
end
EDIT:
Drop down box work but the options arn't wahat I want. I am getting options like # for tenants and # for properties. I would like if I could get the tenants names and the address of the properties instead
_form file code updated with teresko's suggestions
<%= form_for(#lease) do |f| %>
<% if #lease.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#lease.errors.count, "error") %> prohibited this lease from
being saved:</h2>
<ul>
<% #lease.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :tenant_id %><br />
<%= f.select :tenant, options_for_select(#tenants) %>
</div>
<div class="field">
<%= f.label :property_id %><br />
<%= f.select :property, options_for_select(#properties) %>
</div>
<div class="field">
<%= f.label :lease_start %><br />
<%= f.date_select :lease_start %>
</div>
<div class="field">
<%= f.label :lease_end %><br />
<%= f.date_select :lease_end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
First tip : the good practice is to use #properties when you have many properties, not #property. Idem with #tenants.
Then, you can set this in the new or edit page :
<% form_for #lease do |f| %>
<%= f.select :property, options_for_select(#properties) %>
<%= f.select :tenant, options_for_select(#tenants) %>
<% end %>
Next tip is to use a partial named app/views/leases/_form.html.erb to set the previous form, when the new and edit are rendering the same form. Then, your new and edit views will become
<%= render :partial => 'form' %>
To have specific option display, you can read the options_for_select or options_from_collection_for_select docs
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select
<%= f.select :property, options_from_collection_for_select(#properties, 'id', 'name') %>
Choose the best method to your case.

rails accept nested atributes for a polymorphic association

I have an error "Can't mass-assign protected attributes: Upload", but I have assigned it to be accessible.
This is a nested form with a polymorphic association.
Models
class Upload < ActiveRecord::Base
attr_accessible :link, :post_id
belongs_to :uploadable, polymorphic: true
end
class Post < ActiveRecord::Base
attr_accessible :description, :title, :uploads_attributes
has_many :uploads, as: :uploadable
accepts_nested_attributes_for :uploads, :reject_if => lambda { |a| a[:content].blank?
}, :allow_destroy => true
end
I tried too put accept_nested ... for :uploadable but tells me dont exist the association
The action new on the controller is this one
def new
#post = Post.new
#post.uploads.new
end
and here is the form for create
<%= form_for [:admin,#post], remote: true, :html => {:multipart => true} do |f| %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title%>
</div>
<div class="field">
<%= f.label :description%><br />
<%= f.text_area :description %>
</div>
<div>
<%= f.fields_for :upload do |builder| %>
<%= render 'upload_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Upload", f, :uploads %>
</div>
<div class="actions">
<%= f.submit%>
</div>
<% end %>
The partial ...
<fieldset>
<%= f.label :file %><br />
<%= f.file_field :file %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>
Dont think the javascript affects, so Im not going to put it here.
How I cna solve "Can't mass-assign protected attributes" on polymorphic asociations ?
Plz need help on this anyone. Cant belive I cant upload files, looks so simple on tutorials, and Its not working, or I get a Can't mass assign orthe upload its not saved ....
Try to use #post.uploads.build instead of #post.uploads.new
The associated model needs to know the identity of her parent to save the relationship.
I recommend you the following railscast: Polymorphic Association.
#uploads_controller.rb
before_filter :load_uploadable
def create
#upload = #uploadable.uploads.new(params[:upload])
....
end
private
def load_uploadable
resource, id = request.path.split('/')[1, 2] # /posts/1
#uploadable = resource.singularize.classify.constantize.find(id)
end
This line inside your view:
<%= f.fields_for :upload do |builder| %>
Should be this:
<%= f.fields_for :uploadable do |builder| %>
Because the association on the Post model is called "uploadable", not "upload".
For nested attributes to work, you will need to specify the model does accept nested attributes for this model, which can be done by putting this line underneath the belongs_to in your model:
accepts_nested_attributes_for :uploadable
And then you will need to make these attributes accessible, which you can do with this:
attr_accessible :uploadable_attributes

Resources