我正在尝试捕获验证错误并通过 jQuery 返回它们。但是,当推文有效时,它似乎没有方法错误。并且不运行else format.js并触发failure.js.erb
hashtag_controller.rb
定义创建
@hash_create = Hashtag.create_hashtag(params[:hashtag])
Hashlog.create_hashlog(params[:hashtag])
@random_hashtag_pull = Hashtag.random_hashtags_pull
@leaderboard = Hashtag.leaderboard_history_current
respond_to do |format|
if @hash_create
format.html { redirect_to root_path }
format.js
else
format.js { render :action => "failure" }
end
end
end
标签.rb
hashtag_regex = /[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/i
validates :hashtag, :presence => true,
:length => { :within => 3..20 },
:format => { :with => hashtag_regex }
class << self
def create_hashtag(hashtag) #creates new tweetvstweet for inputed hashtag with # for guests
dash = "#"
@hashtag_scrubbed = [dash, hashtag].join.downcase
(User.current_user ? User.current_user.twitter : Twitter).search("%#{@hashtag_scrubbed}", :lang => "en", :count => 100, :result_type => "mixed").results.map do |tweet|
unless exists?(tweet_id: tweet.id)
create!(
tweet_id: tweet.id,
text: tweet.text,
profile_image_url: tweet.user.profile_image_url,
from_user: tweet.from_user,
from_user_name: tweet.user.name,
created_at: tweet.created_at,
hashtag: @hashtag_scrubbed,
view_count: "0",
wins: "0"
)
end
end
end
有效时出错
在 388 毫秒内完成 500 内部服务器错误
NoMethodError (undefined method `create!' for #<Array:0x007ffa911efb20>):
app/controllers/hashtags_controller.rb:16:in `block in create'
app/controllers/hashtags_controller.rb:15:in `create'
无效时出错
Completed 500 Internal Server Error in 900ms
ActiveRecord::RecordInvalid (Validation failed: Hashtag is too short (minimum is 3 characters), Hashtag is invalid):
app/models/hashtag.rb:45:in `block in create_hashtag'
app/models/hashtag.rb:34:in `map'
app/models/hashtag.rb:34:in `create_hashtag'
app/controllers/hashtags_controller.rb:11:in `create'