我工作的帖子的形式比可以有标签。这种关系是Post
和Tag
之间的经典has_and_belongs_to_many
。标签形式的帖子模型
问题是我不能初始化后与标签ID的数组,像这样:
Post.new(tags: [1, 2, 3, 4]) # won't wotk. ActiveRecord expects Tag instances
所以我目前的形式是这样的:
= form_for @post do |f|
= f.text_field :title, placeholder: 'title...'
= f.text_area :body
= fields_for :'post[tags]' do |ft| # hacky. using @post.tags raised 'undefined `model name` for `@post.tags`'
- Post.tags.each do |tag| # I defined Post::tags since I can't Acces Tag class here
= ft.check_box tag.id
= tag.name
= f.submit 'Save'
这种形式我的力量在控制器中进行少许修改,但似乎是一种不好的做法。我也认为我可以重写ActiveRecord :: Base初始化器来允许ID,所以我的第一个例子工作,但肯定我在这里失去了一些东西。