开发者

How do I join records together and seperate them with "-"

I want to join records together and separate them with "-"

I know how to join one table records together like this:

@keywords = @tweet.hash_tags.join("-")

But what if it's HABTM associated tables.

For example.

// BRAND MODEL
has_and_belongs_to_many :categories

// CATEGORY MODEL
has_and_belongs_to_many :brands

If I do this:

@brands = Brand.all  
@brand_categories = @brands.categories.join("-")

I get this result:

#<Category:0x0000010445c928>,#<Category:0x0000010445c7c0>开发者_Python百科,#<Category:0x0000010445c5e0>,#<Category:0x0000010445c400>,#<Category:0x0000010445c270>

Hope you understand my question - thanks.


#join will call #to_s on the items in the Array returned by @brands.categories by default, and it doesn't look like you've defined a custom Category#to_s. Either do so, or be more explicit about the string representation you want; if, for example, a Category has a title attribute, you could use:

@brands_categories = @brands.categories.map(&:title).join("-")


Assuming your Category table has a name field:

@brand_categories = @brands.categories.collect(&:name).join("-")

This will put all of the name values into an array, and then join those.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜