How do I generate a form using a model with single table inheritance? - sti

I have a model Company that has a type field. There are two subclasses Fleet and Dealer.
I know the inheritance is working so I'm now working towards the views working too. However the views/companies/_form.html.erb is producing this error when I click edit on a specific company object on my webpage:
undefined method `dealer_path' for #<ActionView::Base:0x000000000418c0>
Here is the form_with tag:
<%= form_with(model: company, class: "contents") do |form| %>
*CONTENT*
<%end%>
I want to generate the form based on what company type I am looking at and for all the fields to be populated with their corresponding data.
I found this warning on the ROR site (https://guides.rubyonrails.org/form_helpers.html):
When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify :url, and :scope (the model name) explicitly.
But I do not understand exactly what this means and I believe it is the key to my solution. I wish there was an example of this situation on that guide.
Any help or suggestions are welcome and appreciated!
UPDATE
I changed the form_with tag to be:
<%= form_with(model: [:company #company], class: "contents") do |form| %>
and from my understanding this now generates the URL companies/:id/edit
This is closer, and now brings me to the companies edit page but I can't update now because the changes don't persist.
My NEW question now is, what routes should I have set up?
If I'm on localhost:3000/companies and I click 'show company', should this take me to /companies/id: or take me to /dealer/id: / /fleet/id: ?

I have managed to route the app so it will take me to /companies/id regardless of the type value of the object. This works well and all CRUD is working well now too.
I didn't log exactly what it was I changed this time as I just reverted to a previous commit and rebuilt from there.

Related

Multiple form inputs for the same field

I have a Rails model called request_form. In the form I have multiple boxes that can be selected, similar to the "What can we craft for you section" in the following site http://mostlyserious.io/get-started/
I have a field called number_of_guests that can be a handful of values depending on which section is clicked. I plan on using javascript to grab the value of the clicked element and assigning it to the request_no_of_guest param. However, in the form I have that same field rendered 5 times to allow for each selection. What is the best way about this? Is there a better way to handle this? I thought about creating a controller method that loops through each instance of that request_no_of_guests param and determining which instance is populated and then sending that up.
Is this the best way to handle this case?
Well as you did not provide any useful detail I will answer as I understood the question.
Let’s have a quick look at what this might look like. To do so, we’ll imagine a demo app into which you can enter the name of a professor and select their various areas of expertise.
Professor has a field expertise which is String.
The form can be as follows:
<%= label_tag 'expertise_physics', 'Physics' %>
<%= check_box_tag 'professor[expertise][]', 'Physics', checked('Physics'), id: 'expertise_physics' %>
<%= label_tag 'expertise_maths', 'Maths' %>
<%= check_box_tag 'professor[expertise][]', 'Maths', checked('Maths'), id: 'expertise_maths' %>
alter app/controllers/professors_controller.rb
from
params.require(:professor).permit(:name, :expertise)
to
params.require(:professor).permit(:name, expertise:[])
Then in app/models/professor.rb
before_save do
self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("expertise")
end
and in /app/helpers/professors_helper.rb
def checked(area)
#professor.expertise.nil? ? false : #professor.expertise.match(area)
end
This way you can grab the different values selected in the form into the expertise attribute, however this is not recommended if you are planning to query the selected options. The right way would be create a new model called Expertise and then create the relationship professor has_many expertises.
But if you are looking for something simple, then use the above code.

How can I pull data in a controller and form for one model that is in a different model with out a foreign key relationship?

I am new to rails and haven't really done to much with data outside of the model.
I have a form that references a table controller for files. I want to add an dropdown that will display a list of projects from a project table for the user to assign a the file to a project if they want too. Assigning a project is not a requirement. The file can be unassigned to a project. I do have a project_id column in the file table for those projects assigned but it is allowed to be null and I did not build a relationship because I need to have cases where there are none.
Can someone please tell me how to do this?
When they evaluate the file, the screen posts back with a save or update button depending if it has already been saved in the database.
At the same time as the save and update pop up on the right I want to display a list box of the projects with an assign project button. If new just a list, if update either just a list because not assigned or display the selected value in the list if already assigned, while allowing them to change it from the list if desired.
In the file controller method that posts back to the UI I have this code:
#file_alias_filedata = FileAliasFiledata.all
#projects = Project.all
for update
#projects = Project.find(params[:id])
In the form I have this code:
<p> <label> Select Project to Assign:</label> <br />
<%= select_tag 'projects', (#projects.present? ? options_for_select(#projects, #selected_project) : []) %> </p>
The form runs but I get this in the dropdown box:
#<Project:0x))7ff531ab4518>
Can someone please help me figure out how to accomplish my task and why I see the strange box value?
What am I doing wrong?
Thank you for your help!
Assigning a project is not a requirement. The file can be unassigned
to a project. I do have a project_id column in the file table for
those projects assigned but it is allowed to be null
From the docs:
belongs_to(name, scope = nil, options = {}) public
Specifies a
one-to-one association with another class. This method should only be
used if this class contains the foreign key. If the other class
contains the foreign key, then you should use has_one instead. See
also ActiveRecord::Associations::ClassMethods’s overview on when to
use has_one and when to use belongs_to.
Methods will be added for retrieval and query for a single associated
object, for which this object holds an id:
association(force_reload = false)
Returns the associated object. nil is returned if none is found.
Likewise,
has_many(name, scope = nil, options = {}, &extension) public
Specifies
a one-to-many association. The following methods for retrieval and
query of collections of associated objects will be added:
collection(force_reload = false) Returns an array of all the
associated objects. An empty array is returned if none are found.
But belongs_to() and has_many() are supposed to make things more convenient for you. You certainly do not have to use them.
Next,
and why I see the strange box value? What am I doing wrong?
You see the strange value for the same reason the following two loops display different things:
class Dog
attr_reader :name
def initialize(name)
#name = name
end
end
#dogs = [
Dog.new("Sam"),
Dog.new("Betty"),
Dog.new("Pete"),
]
#dogs.each {|dog| puts dog}
#dog_names = #dogs.map {|dog| dog.name }
#dog_names.each {|dog_name| puts dog_name}
--output:--
#<Dog:0x0000010099a308>
#<Dog:0x0000010099a2b8>
#<Dog:0x0000010099a268>
Sam
Betty
Pete
You will see the same result if you do something like the following in a view:
<div>
<%= select_tag "dog", options_for_select(#dogs) %>
</div>
<div>
<%= select_tag "dog_name", options_for_select(#dog_names) %>
</div>
If you read the docs here:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select
...you will see several examples, which should make it clear that options_for_select() takes an argument that is:
An array of Strings.
A Hash where both the keys and values are Strings.
An enumerable that iterates over some Strings.
etc.
Do you see a pattern? It's Strings! options_for_select() needs an argument that consists of Strings. If the argument is not a collection of Strings, e.g. an array of project objects, then options_for_select() tries to convert the objects to strings by calling to_s() on the objects. And the default to_s() method is Object#to_s() which is inherited by all objects and produces a string containing the class name and the object_id.
I am also new to rails, but I think you can try using the options_from_collection_for_select method.
<%= select_tag :search_state, options_from_collection_for_select(State.find(:all, :select => :name), :name, :name) %>
Hope this help. Cause it certainly helped me.

KnockoutJS and Property-Dependent Create/Edit-View (Master/Detail Scenario)

I am having trouble creating a property-dependent create/edit-view in KnockoutJS.
Here's the thing: everything I create are "People" of sorts - it could be a Healthcare Professional, Plumber, Mechanic or Engineer. Depending on what kind/type of person it is, I need to enter different data.
Here an example:
Healthcare Professional: Name, Telephone, Hospital, etc.
Plumber: Name, Telephone, Crafts, etc.
Engineer: Name, Telephone, Specialities, etc.
What I can do is create properties on my ViewModels such as "showCity", "showHospital" and so on to hide individual form-fields.
However, for the sake of separation, I would like to use entirely different forms: again, I could set the respective form to only show if the condition is met.
However, I would like KnockoutJS to only render the respective form that should be used (the Person's type is always determined when it is first created - it cannot be changed).
What I don't end-up doing is have one form that is shown and ten that are there (and data-bound) but hidden.
I tried using the "if" binding like so: <div data-bind="with: $root.selectedPerson"><form data-bind="if: $data.type='mathematician'"></form></div>, but to no avail.
Would anybody know what the best-practice is in this case?
Your if binding is setting the $data.type value, not comparing it. Try:
<div data-bind="with: $root.selectedPerson"><form data-bind="if: $data.type() === 'mathematician'"></form></div>
Although this is fine, I always try to avoid code in my data-binding markup. I would try and create a computed that would return the resulting true/false of the comparison, but in your situation, you would need one for each person type, and that would get tricky. For that, I would turn to templates. You could do:
<div data-bind="template: { name: $root.selectedPerson().type, data: $root.selectedPerson }"></div>
<script type="text/html" id="mathematician">...</script>
<script type="text/html" id="plumber">...</script>
*Note: As of KO version 2.3.0, the name property of the template binding can accept observables. If you're using a previous version, be sure to call the observable in the binding: name: $root.selectedPerson().type()

Symfony2: Entity instantiation upon Form-Submit depending on user selection

I'm working with Symfony2 to set up a form, where a Shelf-Entity can be edited.
A shelf contains a collection of Readable-Entities (e.g. Book, Magazine, etc. - all inherit from Readable).
The user has the possibility to add more Readable-Entities (the form is extended via JavaScript) and from a dropdown he can select the type of Readable he wants to add. Depending on the selected dropdown-value, different form fields are rendered. So far so good.
Now, when the form is submitted to the server, depending on the Readable-Type the user selected in the form, a different entity-type should be instantiated.
If I don't do anything, Symfony just instantiates the base class Readable (and not Book, Magazine, etc.).
How can I tell Symfony to instantiate the correct type of Readable depending on the selected value from the dropdown?
I tried with FormEvent-Listeners, but:
in PRE_SUBMIT I only get an array containing the "raw" form data with $event->getData(), i.e. no entities have been instatiated so far. However, at this stage, I still have access to value of the dropdown.
in SUBMIT the form data was already assigned to the appropriate entities. Also the new Readable was already instatiated with the base Readable-Class. But now, I cannot access anymore the value from the dropdown.
What is the correct way to do this?
EDIT
Added a minimal Code-Example for the Shelf FormType:
https://gist.github.com/anonymous/401495b701982adafb96
Code for infinite_form_polycollection:
https://gist.github.com/anonymous/b5f0ed10ca9c52177f01
Have you tried looking at this part of the doc? As "embedding a form" seems to fit your needs.
It seems that there was something wrong with the PHP-Files of the PolyCollection in the vendor-directory, because after removing everything related to the Infinite Form Bundle from the vendor-dir and reinstalling it with composer, everything is working now. But thanks for your efforts YoannCh

Binding two objects of the same type in an action

I have a page that collects information on two objects of the same type. When the page is submitted the action that handles the processing of the information submitted is attempting to use model binding, something similar to:
public ActionResult Submit(Person parent, Person child)
{
//Do some stuff
}
It manages to bind one of them successfully but not the other. Does anyone have any suggestions/resources etc that could help me get this to work?
If needed I can gut/rename and post the actual code for the various pieces.
The solution to this is very much similar to the solution to my question that I posted the other day (I wouldn't at all call this a dupe though).
What you need to do is just include the parameter name in your inputs, eg:
<%: Html.TextBox("Parent.Name") %>
.....
<%: Html.TextBox("Child.Name") %>
and it should all automagically work.
(I think this is MVC2 only, you didn't mention whether you were using 1 or 2)
Would it make sense to have a ParentChild Model with two person instances in it?
I don't think I've seen any examples like this trying to bind two models on post.