开发者

String concatenation not possible?

So over the last 2 hours, I've been trying to fill a combobox with all my users. I managed to get all firstnames in a combobox, but I want their full name in the combobox. No problem you would think, just concatenate the names and you're done. + and << should be the concatenation operator to do this.So this is my code:

<%= collectio开发者_StackOverflown_select(:user, :user_id, @users, :user_id, :user_firstname + :user_lastname, {:prompt => false}) %>

But it seems RoR doesn't accept this:

undefined method `+' for :user_firstname:Symbol

What am I doing wrong?


What you need to do is define a method on the User model that does this concatenation for you. Symbols can't be concatenated. So to your user model, add this function:

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

then change the code in the view to this:

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

Should do the trick.


This isn't really rails giving you an error, it's ruby. You're trying to combine the symbols :user_firstname and :user_lastname

A symbol is a variable type, just like integer, string, or datetime (Well technically they're classes, but in this context we can think of them as variable types). They look similar to strings, and can function similarly to them, but there is no definition for the behavior of symbol concatenation. Essentially you're trying to send the method user_firstnameuser_lastname which is just as non-sensical as trying to concat two Symbols.

What you need to understand is that this parameter is looking for a method on your User object, and it won't understand the combination of two symbols. You need to define a method in your model:

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

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

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

Also, it's considered poor practice to prefix every single column with the table name. user.user_firstname just looks redundant. I prefer to drop that prefix, but I guess it's mostly up to personal preference.


The arguments for value and display attribute are method names, not expressions on a user object.

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

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

The docs are pretty useful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜