最近在研究@happypeter的视频网站代码,自己写后台代码。不过在测试 tag 更新的时候出现了一个奇怪的问题。在更新 episode 的 tag 的时候,后台卡住,不提交事务。如果 Ctrl+C 关掉 Webrick 就会出现下图 Shut down 以下的内容,事务进行提交:
而用 rails c 跑一下,结果是可以提交:
请各位参谋一下。关键代码:
episode.rb
class Episode < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
...
def tag_names=(names)
# 都处理为数组
new_names = names.strip.split(';').map(&:strip)
old_names = tag_names.split(';')
self.tags = Tag.with_names(new_names, old_names)
end
def tag_names
tags.map(&:name).join('; ')
end
...
end
tag.rb
class Tag < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :episodes, through: :taggings
def self.with_names(new_names, old_names)
#only the added and shared names will return
result = []
added_names = new_names - old_names
deleted_names = old_names - new_names
shared_names = new_names & old_names
#first, handle added_names
added_names.each do |added_name|
tag = Tag.find_by(name: added_name)
if tag.present?
tag.ep_count += 1
tag.save
else
tag = Tag.create(name: added_name, ep_count: 1)
end
result << tag
end
#handle deleted_names
deleted_names.each do |deleted_name|
tag = Tag.find_by(name: deleted_name)
if tag
tag.ep_count -= 1
if tag.ep_count < 1
tag.destroy!
else
tag.save
end
end
end
#handle shared_names
shared_names.each do |shared_name|
result << Tag.find_by(name: shared_name)
end
result
end
end
episodes_controller.rb
class EpisodesController < ApplicationController
.......
def update
respond_to do |format|
if @episode.update(episode_params)
format.html { redirect_to @episode, notice: 'Episode was successfully updated.' }
format.json { render :show, status: :ok, location: @episode }
else
format.html { render :edit }
format.json { render json: @episode.errors, status: :unprocessable_entity }
end
end
end
.......
private
# Use callbacks to share common setup or constraints between actions.
def set_episode
@episode = Episode.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def episode_params
params.require(:episode).permit(:name, :description, :revision, :published_at, :tag_names)
end
再次对大家的帮助表示感谢。祝各位工作好心情。谢谢!