I'm really stuck in a issue.
I've a RoR application in which I'd like to populate select_tag with filtered options lets say Physicians. Here is my select_tag in view:
<%= select_tag "phyID",options_from_collection_for_select(#physicians,'id','fullNamePhy'),:include_blank => true %>
In controller I have
#physicians=User.find_by_userType('Physician')
but I'm getting error:
undefined method `map' for #<User:0x3b09820>
It seems like I have to use User.all instead of User.find. Please let me know any work around. Thanks in advance
This should work:
#physicians = User.where(userType: 'Physician')
You're getting error because options_from_collection_for_select expects object that behaves like Array, for example ActiveRecord::Relation instance. But find_by_* dynamic finder returns object representing singular record, User instance in this case.
BTW, column names in Rails are by convention named with underscore instead of camel case , like user_type.
You can use dynamic find_all_by finder
#physicians = User.find_all_by_userType('Physician')
find_by_column_names returns single record. Where as select_tag expects collection/array of record
Related
How can I use where condition in options select? The following code is not working:
<%= options_from_collection_for_select(#group,:groupname, :groupname).where(User_id: #user.id)%>
Can anyone help on this?
options_from_collection_for_select takes a collection of records and options and returns a HTML string. So that of course won’t work as you are calling .where on a string.
You need to call it on the collection instead.
<%= options_from_collection_for_select(#group.where(User_id: #user.id), :groupname, :groupname) %>
In html.erb I have:
<%= ContactDescribe.where(["contact_describe_id = ?", "12"]).limit(1).pluck(:borrower_or_lender_text) %>
The field is retrieved successfully. But returns an array element. I need to learn how to convert that element to a string.
In addition to Deepak's answer, you can also convert the Array into a "Sentence" String
<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).to_sentence %>
Recommendation:
As pointed out by TheChamp, it is best practice to already "prepare" the values needed in the views as instance variables from the controller. See my recommended refactor
# controller
def YOUR_ACTION_NAME
#contact_describe = ContactDescribe.where(contact_describe_id: 12).first
end
# view
<%= #contact_describe.borrower_or_lender_text %>
Note: you won't even need pluck anymore unless you have other reasons why you want limit(1)
The issue here is that where returns a collection - something similar to an array, just in ActiveRecord - no matter what limit you set on it. To retrieve the information you would use .first or [0] since you always only return one object.
But, since you are looking for a specific ContactDescribe object. Do this instead:
ContactDescribe.find_by(contact_describe_id: 12).borrower_or_lender
Additionally there two things you should improve in your code.
1: Logic should go into the controller or the model. A view is solely here to show objects.
2: What is up with the contact_describe_id field? Why not call it id. It seems redundant. Isn't user.id more convenient than user.user_id?
You can make use of join
<%= ContactDescribe.where(contact_describe_id: 12).limit(1).pluck(:borrower_or_lender_text).join(',') %>
I want to be able to select a city from an existing array of cities.
I have stored the cities in an array in the ControllerName controller as a global variable
$cities = ["city1"...."city20"]
and I want to be able to access them via : <%= p.select(:city, $cities{ |c| [c.name, c.id]}) %>
but then I receive the error message undefined method name for 'city1'.
How can I select from that existing array?
Should I make some controller for cities?
Update #1
I came to make this code
$cities=['city1',...'city20']
#city = Array.new
i = $cities.size
i.times do |x|
#city[x] = City.new
#city << $cities[x]
end
and instead of undefined methodname' for "City1":StringI gotundefined method name' for "City20":String
PS : the table of cities has a column named 'name', so the problem isn't particularly there
Update #2 : Issue Solved
After reading a bit in this Rails Documentation I was able to make a little improvement on my code and I actually could solve the issue.
In my form , I have edited the code to that :
<%= p.select(:city, options_for_select( #cities_array ) )%>
And in my ControllerName Controller , I have put this :
$cities.length.times do |x|
#city = City.new({:name => $cities[x]})
#city.save
end
#cities_array = City.all.map { |city| [city.name, city.id] }
And that was all to it.
If you have any alternative solution , be it simpler or more complex, please share it as an answer.
You have multiple options to insert data into your database.
The first one. Add this on a migration:
rails generate migration add_cities_rows
inside your migration you can add something like:
cities = ['city1', 'city2', 'city3']
cities.each {|city| City.create(name: city)}
then you can run: rake db:migrate
You can add the same logic in db/seeds.rb file so if you want to regenerate your database running rake db:setup it will do the magic.
In your view(where you are using the select helper you can use the following sintaxis to fill the select:
<%= p.select :city, City.pluck(:name, :id) %>
So in your controller yo don't needto add any logic
This error is because 'city1' is a string and you are calling name method on a String object which isn't defined.
Probably you may have a City Model defined and must be having a database column **name within. So name method will be defined for a City object
Here, $cities is an array of strings which should be an array of City Objects instead.
Yes, make a controller for Cities and collect city objects array from these array of strings and pass on that to view
i tried this here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
exactly this:
<%= collection_select(:sportlers, :sportlers_id, Sportler.all, :id, :name) %>
But there dont is written, how to get the selected value from the collection_select.
Im helpless, do you work with somethings like this?
I think collection_select will take the first two parameters, the object and the method, and use the values to make a hash, so in your case, you can access the values in your controllers like:
params[:sportlers][:sportlers_id]
In my method via some calculations a get data, then i need to view it in view, but if write
#ar.each do |a|
when i have only one record i get error, also when i have one error each is bad idea. So how to do this this?
So i have such code in method:
non_original = []
#articles.each do |a|
non_original << get_non_tecdoc("LA44", 1, "KNECHT")
end
#non_original = non_original
get_non_tecdoc returns object, or nothing...
So in view i have:
-#non_original.each do |no|
=no.brand
=no.description
=no.price
=no.quantity
But what to do if #non_original has one record, then #non_original.each gives error. So how to do check in view? If #non_original has one record, than simple #non_original.brand etc, but if more than one, than use each loop?
This will work with #ar as a single value as well as an array:
Array(#ar).each do |a|
p a
end
This Array is a method on Kernel.
<%= debug #ar %>
This will give you a nice YAML format to look at in your view (assuming ERB).
EDIT: I believe this is what you want, since you're not interested in debugging.
In your controller, use the splat operator to convert a singleton element to an array (it doesn't modify arrays):
#ar = *#ar
Then #ar.each will work as expected in your view.
Alternatively, you could check in your view:
<% if #ar.is_a?(Array) %>
<% #ar.each ... %>
<% else %>
<%= #ar %>
<% end%>
Why don't you try using #ar.inspect and output it to the console to see the instance variables contents.
As long as #ar is an array you should not get a error. If you are returning one record change it to an array with one record.
If you are using active record query interface like the "where" clause; it will return an array with 0 or more active_record objects. If you use find it will return one instance of an active_record object.
So if your method that queries is using the active record where clause #ar should always return an array.
Please try this:
Tablename.find_by_table_id
Example:
if account_id is 10 then, take following example,
#getResults = Account.find_by_account_id(10)
It will gives single record.
we can get values using #getResults.id,#getResults.name ....like wise.