我有一些用户,这些用户可以拥有许多帖子,每个帖子都可以有许多标签。我使用has_and_belongs_to_many关系在帖子和标签之间实现了这一点。
当创建新帖子时,用户可以使用逗号分隔的值列表对其进行标记(就像在SO上发布新问题时一样)。如果任何一个标签不存在,则应自动创建。这是帖子的_fields.html.erb部分:
<%= form_for @post do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<h1 class="post"><%= t(:new_post_message) %></h1>
<div class="field">
<%= f.label t(:title) %>
<br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label t(:tag).pluralize %>
<br />
<%= f.text_field :tags %>
</div>
<div class="field">
<%= f.label t(:text) %>
<br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit t(:post_verb) %>
</div>
<% end %>
使用 f.text_field :tags 目前会生成一个带有文本 [] 的输入元素。
我现在还没有在 posts_controller.rb 中使用标签,因为我不确定该如何获取和拆分参数中的字符串值:
def create
@post = current_user.posts.build(params[:post])
if @post.save
redirect_to root_path
else
@stream = []
render 'pages/home'
end
end
有人之前解决过这个问题吗?非常感谢。
attr_accessible :title, :content, :tag_list
。 - Vlad Sabevattr_accessible
的观点很好。再提一个小风格问题,我在重新阅读我的代码时注意到,将范围添加到标签中可能是值得的,例如scope :called,lambda { |n| where('tags.name = ?',n) }
,然后使用它来替换where(...)
方法。 - Chris BaileyTag.where('name=?', name.strip).first or Tag.create(:name => name.strip)
- Rafael Vega