如何接受以逗号分隔的列表来构建模型标签? [英] How to accept comma-delimited list to build tags for model?

查看:105
本文介绍了如何接受以逗号分隔的列表来构建模型标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于当前应用程序的灵活性有限,我将关闭acts_as_taggable_on.取而代之的是,我将标签从头开始构建为自己的模型.但是,我已经错过了表单的"@ model.tag_list"方法,该方法会分割以逗号分隔的用户输入并制作单个标签.我的可标记"模型是一个视频,我很好奇如何编写一种基本上可以像"tag_list"一样工作的方法?

I'm switching off of acts_as_taggable_on because of limited flexibility for my current application. Instead, I'm building my tags from scratch as their own model. However, I already miss the "@model.tag_list" method for forms, that would split up comma-delimited user input and make individual tags. My "taggable" model is a video, and I'm curious how to write a method that can essentially act like the "tag_list"?

示例:

<%= form_for @video do %>
  <%= f.text_field :tag_list %>
  ....

提供输入:"one, two, three" 将建立三个标签作为@video的子级.

Given the input: "one, two, three" Would build three Tags as children of the @video.

@video.tags.each do |tag|
  puts tag.name
end

=> one
two
three

编辑

在Tag模型中,我真的很喜欢这样做,以使表单保持混乱.也许作为自定义属性?也许视频模型会更有意义?我知道如何制作自定义方法来返回自定义数据,但不对其进行分配.一些研究以这种方式指出了我(尚未测试)

I'd really like this in the Tag model, to keep form cluttering my controller. Maybe as a custom attribute? Maybe the Video model would make more sense? I know how to make a custom method to return custom data, but not assign it. Some research points me this way (not yet tested)

video.rb

def tag_list=value
  value.split(',').each do |tag|
    self.tags.build(:name => tag).save
  end
end

推荐答案

看来我的示例代码最终可以正常工作

It seems like my example code ended up working

video.rb

def tag_list=value
  value.split(',').each do |tag|
    self.tags.build(:name => tag).save
  end
end

编辑

还需要添加使其使其以某种形式工作:

Also need to add to get it to work in a form:

def tag_list
  self.tags.join(',')
end  

这篇关于如何接受以逗号分隔的列表来构建模型标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆