Is string concatenation impossible?

So, in the last 2 hours, I tried to populate combobox with all my users. I managed to get all the firstnames in combobox, but I want their full name to be in combobox. There are no problems that you might think, just put the names together and you're done. + and <there must be a concatenation operator for this. So this is my code:

<%= collection_select(:user, :user_id, @users, :user_id, :user_firstname + :user_lastname, {:prompt => false}) %> 

But RoR doesn't seem to accept this:

 undefined method `+' for :user_firstname:Symbol 

What am I doing wrong?

+4
source share
3 answers

What you need to do is define a method in the user model that performs this concatenation for you. Symbols cannot be combined. So, add this function to your user model:

 def name "#{self.first_name} #{self.last_name}" end 

then change the code in the view to the following:

 <%= collection_select(:user, :user_id, @users, :user_id, :name, {:prompt => false}) %> 

Gotta do the trick.

+14
source

In fact, these are not rails giving you an error, this is a ruby. You are trying to combine the characters :user_firstname and :user_lastname

A symbol is a variable type, as an integer, string or datetime (well, technically they are classes, but in this context we can consider them as variable types). They look like strings and can function similarly to them, but there is no definition of character concatenation behavior. Essentially, you are trying to send the user_firstnameuser_lastname method, which is as insensitive as trying to concatenate two characters.

What you need to understand is that this parameter is looking for a method for your User object, and it will not understand the combination of two characters. You need to define a method in your model:

 def fullname [user_firstname, user_lastname].reject{|v| v.blank?}.join(" ") end 

This will return your first + name for you, and then in the parameter you should send :fullname (because the method that it will call for each user object in the collection):

 <%= collection_select(:user, :user_id, @users, :user_id, :fullname, {:prompt => false})%> 

In addition, he believed that it was bad practice to prefix each column with the table name. user.user_firstname just looks redundant. I prefer to refuse this prefix, but I assume that it mainly depends on personal preferences.

+4
source

The arguments for the value and display attributes are method names, not expressions for the user object.

To control the format more precisely, you can use select instead:

 select("user", "user_id", @users.each {|u| [ "#{u.first_name u.last_name}", u.user_id ] }) 

docs are pretty useful.

0
source

All Articles