Rails how to fetch data from model specified in form select? - ruby-on-rails

Let's say I have this form select :
<%= form_with(model: task, local: true) do |form| %>
<%= form.select(:person_id, Person.all.collect {|c| [c.person_name, c.id]}, {prompt: "Select a person"}, {class: 'col-md-12'}) %>
In my task controller, in my create def, I'd want to be able to fetch the person_name but it turns out I can't. For example, I can fetch the id by doing #task.person_id, but I can't do #task.person_name. How would I achieve this? I'm thinking about maybe options_for_select or maybe collection_select, but I'm very unsure.
Anyone has an idea? Thank you :)

What if you change collect to select
may that helps
#autoComplete = Prom.select('promname').collect { |p| p.promname }

Maybe you can access the person name by
#task.person.person_name
or if you want to get person name from task,
add this in task.rb
def person_name
self.person.person_name if !self.person_id.nil?
end
then you can use #task.person_name in your controller

Turns out I fixed it by doing this in my def create of the controller :
name = #task.person_id
#person = Person.find(name)

Related

How to exclude a certain selection from a collection_select list?

Simply I have a collection_select which allows a user to select any users that share the same business.id. It uses the list #colleagues created in Ruby:
#events_controller#new
#colleagues = User.where(business_id: current_user.business_id)
#events/new.html.erb
<%= f.collection_select :id,
#colleagues,
:id,
:full_name %>
But at the moment, this list includes the current_user, which I do not want to happen (the user should not be able to select them self). Is there a way I can exclude the current_user from this list from querying the database? I am using SQLite.
Thank you, and any further explanation would be much appreciated as I am new to Ruby and SQL.
#colleagues = User.where(business_id: current_user.business_id).where.not(id: current_user.id)
You might pass to collection_select something like
#colleagues.reject {|user| user.id == current_user.id }
This code works for me in rails 6.0.0
form.collection_select :parent_id, Collection.all.where.not(id: collection.id), :id, :title

Select field in Rails simple form gem returns object (hex) address

I am using a has_many through relationship for project_assignment, expence_types and assignment_expences tables.
I my simple form for adding new expences, i have:
<%= f.association :project_assignment, prompt: 'choose...', collection: ProjectAssignment.where('active = ?', true).order(:task) %>
This should show task description from field task (table project_assignments) but it returns an object address.
I have another example on this same form:
<%= f.association :expence_type, prompt: 'choose...', collection: ExpenceType.where('active = ?', true).order(:name), right_column_html: { class: 'col-md-1 col-lg-1' } %> That works just fine. Shows the name. I've read that it shows addresses when converting object to string, but I can't make this to work.
Any help would be appreciated.
Please check that your ProductAssignment model defines a to_s instance method, returning the attribute you want to display.

Simple - getting record id instead of desired attribute

This is a really simple question but I am new. I am trying to create a dropdown menu with values populated from the model. However, instead of displaying the city names, I am getting the record id's like: 0x007fee0b7442c0 (not sure if these are called id's, I think there is another term).
Controller:
#cities = City.find(:all, select: "name")
View:
<%= f.select(:city, #cities) %>
What am I doing wrong?
If you want just the name attribute from the database then do:
#cities = City.pluck(:name)
# => ["Sydney", "Melbourne", "Canberra"]
Try: select(object, method, choices, options = {}, html_options = {})
#cities = City.select(:name)
<%= f.select(:city, #cities.collect {|p| [ p.name, p.name ] }) %>
There is a guide to using collection_select here
http://www.fmhcc.com.au/ruby/rails/using-collection_select-in-rails/
You can also improve on #cities = City.find(:all, select: "name") by instead doing
#cities = City.pluck(:name)
If you want to display city name in the select box, and you want to pass the city id as a parameter on form submit, use this
f.select :city, #cities.map {|c| [ c.name, c.id ] }

Rails Form_For Select With Dual Purpose

I have form for adding a new job. On my form I have a select drop-down list. I need to associate the new job to a customer. The following works great.
<%= f.collection_select :customer_id, Customer.all, :id, :business_name %>
But, what if I want to also be able to send in a customer_id to the new form? Can I have the form's select drop-down show all the possible customers, as above, but have it auto select the customer_id I pass into the form, if a customer_id is passed in?
url = ...jobs/new
OR
url = ...jobs/new?customer_id=5
I apologize if I did not explain this well enough.
Thanks in advance.
--jc
I think you do what you're trying to achieve this by populating the customer_id field on the job you're creating in your controller if customer_id is present in the request params. This should make that particular customer be the initially selected option in the form.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
e.g. Something like.
if params[:customer_id].present?
job.customer_id = params[:customer_id]
end
If you declaring the instance variable #customer in your controller action then you can use selected option as:
<%= f.collection_select :customer_id, Customer.all, :id, :business_name, {:selected => #customer.id} %>

Array as Parameter from Rails Select Helper

I'm working on a legacy project that is using acts_as_taggable_on which expects tags to come in arrays. I have a select box allowing users to select a tag on a Course in a field called categories. The only way mass assignment create will work is if params looks like this params = {:course => {:categories => ['Presentation']}}. I've currently a view with this helper:
<%= f.select 'categories', ['Presentation' , 'Round Table' , 'Demo', 'Hands-on'] %>
Which will give me a parameter like params = {:course => {:categories => 'Presentation'}}. This doesn't work since Acts as tag gable apparently can't handle being passed anything other than a collection.
I've tried changing categories to categories[] but then I get this error:
undefined method `categories[]' for #<Course:0x007f9d95c5b810>
Does anyone know the correct way to format my select tag to return an array to the controller? I'm using Rails 3.2.3
I didn't work with acts_as_taggable_on, but maybe this simple hack will be suitable for you? You should put it before mass-assignment.
category = params[:course][:categories]
params[:course][:categories] = [category]
If you are only going to allow the selection of ONE tag, you could do:
<%= f.select 'categories', [['Presentation'] , ['Round Table'] , ['Demo'], ['Hands-on']] %>
Each one item array will have first for the display value, and last for the return value, which in this case will both return the same thing, as the first element of the array is the same as the last element when the array as one element.
Seems like select doesn't give you that option.
If I understand correctly, one option might be to use a select_tag instead and just be explicit about where you want the selection in the params:
<%= select_tag 'course[categories][]', options_for_select(['Presentation' , 'Round Table' , 'Demo', 'Hands-on']) %>
That ought to get your params the way you need them.
Here's what I'm using for one of my projects:
<% options = { include_blank: true } %>
<% html_options = { required: true, name: "#{f.object_name}[#{resource.id}][days][]" } %>
<%= f.select :days, DAYS, options, html_options %>
Without html_options[:name], Rails handles the name of the select tag and spits out something like
service[service_add_ons_attributes][11][days]
but I need
service[service_add_ons_attributes][11][days][]
So I override it.
Hope that helps.

Resources