【问题标题】:Rails split string value as group of objectRails 将字符串值拆分为对象组
【发布时间】:2013-07-19 08:41:10
【问题描述】:

我目前从一个表单中收到一个看起来像这样的字符串:

one tag,another tag,yet another

在我的 Rails 应用程序中,我实现了一个多态关联 :taggable 以管理我系统上的标签(分类)。我现在想要的是将这些值保存在数据库中,当然,代码越少越好。我的表格结构看起来像这样:

// Assocition table
TermRelationship(id: integer, taggable_id: integer, taggable_type: string, created_at: datetime, updated_at: datetime)

// Term table (tag)
Term(id: integer, name: string, created_at: datetime, updated_at: datetime, type: string)

// Blog table
Blog(id: integer, title: string, body: text, created_at: datetime, updated_at: datetime)

到目前为止,我所做的是将这些值拆分为一个数组:

tags = params[:blog][:tag].split(/,/)

现在我唯一能想到的就是有一个循环来逐个添加每个值。但我确信还有另一个类似“Rails/Ruby”的方法。

感谢您的帮助

【问题讨论】:

    标签: ruby-on-rails tags save polymorphism


    【解决方案1】:

    不要重新发明轮子。看看https://github.com/mbleigh/acts-as-taggable-on

    【讨论】:

    • 太棒了,非常感谢。因为我刚开始使用 Rails,所以我想这样做是出于学习目的。稍后会这样做,因为我想知道它在引擎盖下是如何工作的。无论如何,再次感谢
    猜你喜欢
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多