开发者

Rails Why does acts_as_taggable not need to be in a nested form to create tags?

开发者 https://www.devze.com 2023-02-16 13:44 出处:网络
When I have a relation such as: class Programmer < ActiveRecord::Base has_many :projects has_many :assignments, :through => :projects

When I have a relation such as:

class Programmer < ActiveRecord::Base
    has_many :projects
    has_many :assignments, :through => :projects
    acts_as_taggable
end


class Assignment < ActiveRecord::Base
    has_many :projects
    has_many :programmers, :through => :projects
end

Entering both programmer and assignment data in a single form requires me to have a nested form. Why is it that when I have a field for tags, tags doesn't need to be in a nested form?

for example, this doesn't work

<%= form_for(@programmer) do |p| %>
    &l开发者_StackOverflow社区t;%= p.label :name %><br />
    <%= p.text_field :name %><br />
    <%= p.label :assignments %><br />
    <%= p.text_field :assignments %><br />
    <%= p.submit %>
<% end %>

but why does this work?

<%= form_for(@programmer) do |p| %>
    <%= p.label :name %><br />
    <%= p.text_field :name %><br />
    <%= p.label :tag_list %><br />
    <%= p.text_field :tag_list %><br />
    <%= p.submit %>
<% end %>


The less detailed answer is that acts_as_taggable_on handles tag creation when you use tag_list=.

An example IRB session:

$> photo = Photo.last
$> photo.tag_list # ['outer space', 'andromeda']
$> photo.tag_list = "outer space, andromeda, galaxy"
$> photo.tag_list # ['outer space', 'andromeda', 'galaxy']
$> photo.save
# checks the db for existing outer space, andromeda, and
# galaxy tags on the photo, creates any missing ones,
# deletes any ones it previously had but you didn't specify

acts_as_taggable_on can reasonably implement this behavior in this method because the library can assume you're wanting to check for dups, and delete anything you didn't provide. To do this by default on any generic association would be bad :)

0

精彩评论

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