0
레일스를 사용하여 태그 된 블로그 시스템에서 작업하고 있습니다. 이제 조인 테이블을 사용하여 작동하지만 성능에 대해서는 의심의 여지가 있습니다.레일스 activeRecord 패치 및 커밋
이제 블로그와 관련 태그를 만들 때마다 모든 단일 구문을 데이터베이스에 커밋합니다. 나는이 모든 문장을 패치하고 데이터베이스에 한 번만 커밋해야한다는 것이 더 나은 방법이라고 생각한다. 레일에서도 가능합니까?
로그 덤프를 만듭니다
Started POST "/articles" for 127.0.0.1 at 2014-08-29 15:30:48 -0400
Processing by ArticlesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"K4rWQEh0810X2jMe/Z9pC/PN2WeOcO0F0TkjKUZTPec=", "title"=>"test27", "text"=>"ddddd", "tag"=>"a,k,g", "commit"=>"Submit"}
Unpermitted parameters: utf8, authenticity_token, tag, commit
(0.9ms) BEGIN
SQL (0.3ms) INSERT INTO `articles` (`created_at`, `text`, `title`, `updated_at`) VALUES ('2014-08-29 19:30:48', 'ddddd', 'test27', '2014-08-29 19:30:48')
(0.2ms) COMMIT
Tag Load (0.3ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`name` = 'a' LIMIT 1
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO `articles_tags` (`article_id`, `tag_id`) VALUES (28, 1)
(0.2ms) COMMIT
Tag Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`name` = 'k' LIMIT 1
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `tags` (`name`) VALUES ('k')
(0.1ms) COMMIT
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `articles_tags` (`article_id`, `tag_id`) VALUES (28, 17)
(8.3ms) COMMIT
Tag Load (0.3ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`name` = 'g' LIMIT 1
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `tags` (`name`) VALUES ('g')
(0.1ms) COMMIT
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO `articles_tags` (`article_id`, `tag_id`) VALUES (28, 18)
(0.2ms) COMMIT
모델 디자인 : 작업을 마무리,
def create
@article = Article.new(article_params)
tag_arr = params[:tag].split(',')
if @article.save
tag_arr.each do |name|
tag = Tag.find_or_create_by(name: name) # create a new tag only if tag.name not exist
@article.tag << tag
end
redirect_to @article
else
render 'new'
end
end