0
嗨,我是新來的鐵軌,我想知道什麼是誰在HBTM關係中保存依賴對象的最佳方式。在has_and_belongs_to_many關係中保存依賴對象的最佳方法?
具體來說,我有兩個類崗位和標籤
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
我有一個遷移來建立的連接表
class AddPostsTagsJoinTable < ActiveRecord::Migration
def self.up
create_table :posts_tags, :id => false do |t|
t.integer :post_id
t.integer :tag_id
end
end
def self.down
drop_table :postss_tags
end
end
一切都很好了這裏
所以我有一個PostsController從我處理創建,更新和刪除的帖子,我想封裝標籤,以便創建是通過PostsController ...像這樣:
class PostsController < ApplicationController
#... code removed for brevity
def create
@post = current_user.posts.build(params[:post])
if @post.save
tag_names = params[:post][:tags].strip.split(' ')
tag_names.each do |t|
#see if the tag already exists
tag = Tag.find_by_name(t);
if tag.nil?
@post.tags.create!(:name => t)
else
@post.tags << tag #just create the association
end
end
flash[:success] = "Post created."
redirect_to(user_posts_path(current_user.username))
else
@user = current_user
render 'new'
end
end
end
我不知道我應該如何處理我的標籤(一個或多個)的創建,因爲如果我只是叫
@post.tags.create!(:name => t)
這將創建在標籤表中重複記錄(即使:uniq的= > true在模型中指定)。
因此,爲了避免重複我看到,如果一個標籤已經存在,然後添加像這樣
tag = Tag.find_by_name(t);
if tag.nil?
@post.tags.create!(:name => t)
else
@post.tags << tag #just create the association
end
這是它應該做的方式?
這似乎很昂貴(特別是因爲它是在一個循環中),所以我想知道是否有另一種「更乾淨」的方式來做到這一點? (請忘記幹起來的動作等)
有沒有一種乾淨的方式來創建我的標籤,而無需手動檢查重複?
非常感謝您的幫助!