Rails Scaffold references with select input and Entity label with generators - forms

I'm trying to scaffold an app with Rails 4 and I had this little issue with the foreing keys, forms and Entity names. Here are some details:
rails g scaffold user_type name:string
rails g scaffold user name:string pass:string user_type:references
As you can see there is a simple relationship 1:n between an user_type and a user. An it generates the right scaffold on this case. Here is an image of the form generated,
But what I want as a result of the generator is the next form,
So the first change that I want from rails g scaffold is to generate, at least e 1:n relationships with a select input. And also I'm looking for a solution that involves the Models with a label or something. I need a scaffold command that finally generates this.
Witch means that the Entity user_type has his name attribute has a "presentation label".
I understand that I can create a generator from scratch, but I believe that I'm missing some options at the command line, because the change actually really tiny.
And can come up with a solution that involves inserting the right code in each CRUD but i'm planning to use this into a 150 tables database. Any help?

You can replace the templates that the scaffold generator uses by creating alternative templates in a lib/templates/erb/scaffold folder in your application root.
In this case, you will want to copy the original _form.html.erb template and replace the text field with a collection_select:
<%- if attribute.reference? -%>
<%%= f.label :<%= attribute.column_name %> %><br>
- <%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
+ <%%= f.collection_select :<%= attribute.column_name %>, <%= attribute.name.camelize %>.all, :id, :name, prompt: true %>
<%- else -%>
More details can be read in my post on the subject.

Related

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

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.

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.

RefineryCMS, Upload Image on FrontEnd side

Sorry about quite silly question but after several days of searching I still don't have the answer and I'm realy stackoverfloved about it.
I have refinerycms extension. Like this:
$ rails generate refinery:engine shop name:string logo:image
I want it to be controlled from both backend and frontend of my application.
Have no problems with backend. (Thank you for refinerycms team.)
Have no problems with frontend when the form contains only "name". (Or any other attribute that doesn't have image type).
Have problems with image type attributes.
I don't want frontend user to have the same image editing form as backend users does.
I want the form to be smth like this:
<div class='field'>
<%= f.label :logo , "Logo"%>
<%= f.file_field :logo %>
</div>
And I want images loaded by frontend user to be saved with Refinery::Image.
I bet the problem is only in my frontend controller create action for shops, but I have no clue how it should be overwritten.
Thanks a lot for any suggestion.
In the controller, you will have to pass the 'logo' param to the model as a Refinery::Image instance. To do so, you create an instance of Refinery::Image and merge it to the model.
Example:
logo = Refinery::Image.create(image: params[:shop][:logo])
#shop = Refinery::Shops::Shop.create(params[:shop].merge({logo: logo}))
I have FE form with file_field (:logo) on FE and in my normal controller (not the admin one) I have this method to handle params from request:
def model_params
permitted = params.require(:model).permit!
permitted[:logo] = Refinery::Image.create(image: permitted[:logo])
return permitted
end
to permits params and create image form file.
And then in my create method:
def create
if (#new_beer = ::Refinery::Models::Model.create(model_params))
#do some stuff when it succeeds to create it
redirect_to SOMEWHERE
else
redirect_to SOMEWHERE, notice: "Something went wrong!"
end
end
Hope it can help! :)

Asp MVC 2: Typed Editor Template

(I reference this tutorial in this text)
I want to use the Html.EditorFor (or Html.Editor) helpers.
If a UserControl needs additional data it is passed via
...EditorFor(model => model.Album, new { Artists = Model.Artists, ... })
In the UserControl it's accessed via ViewData[stringKey], ie
... new SelectList(ViewData["Artists"] as IEnumerable, ...
To me this smells a little fishy as I would prefer a strongly typed ViewModel which ensures that specific data is available.
I'm now a little bit stuck as I don't know wheater there's a "typed way" to find or I should accept this way as-is.
How did you solve this issue? Any help appreciated!
Lg
warappa
I would probably change my view model so that I don't need to pass this additional information. You could make for example an album has a collection of artists. Now all tha you will have to do is:
<%: Html.EditorFor(model => model.Album) %>
And in your editor template:
<%: Html.DropDownListFor(x => x.SelectedArtist, new SelectList(Model.Artists)) %>