Comma separated array with a text_field in Rails

后端 未结 1 1007
挽巷
挽巷 2021-02-04 13:27

I have some users that can have many posts, and each of those posts can have many tags. I\'ve implemented that using a

1条回答
  •  误落风尘
    2021-02-04 14:19

    My preference would be to create an attribute on the post.model to read in the tags. e.g.

    app/models/post.rb

    def tag_list
      self.tags.map { |t| t.name }.join(", ")
    end
    
    def tag_list=(new_value)
      tag_names = new_value.split(/,\s+/)
      self.tags = tag_names.map { |name| Tag.where('name = ?', name).first or Tag.create(:name => name) }
    end
    

    Then in your view you can do:

    <%= f.text_field :tag_list %>
    

    instead of :tags

    The post model will accept the tag list, split into tag names, find the tag if it exists, and create it if it doesn't. No controller logic required.

    EDIT This code of course relies on your tag model having an attribute called name (if not just substitute whatever attribute you're storing the tags 'name' in), and that it's unique in the database (i.e. you're using something like validates_uniqueness_of :name in your tags model)

    0 讨论(0)
提交回复
热议问题