我试图在我的模型中使用回调after_find
,我在试图让它实际更新它在after_find
方法中找到的行时遇到了问题。它抛出一个无方法错误
错误
Completed 500 Internal Server Error in 299ms
ActionView::Template::Error (undefined method `+' for nil:NilClass):
1: <div id="hashtags" class="twitter-hashtag-voting-block-v1">
2: <% @random_hashtag_pull.each do |hashtag| %>
3: <div class="span4 twitter-spans-v1" id="<%= hashtag.id %>">
4: <div id="tweet-block-v1" class="hashtag-tweet-database-container">
5: <div class="tweet-block-border-v1">
app/models/hashtag.rb:46:in `update_view_count'
app/views/shared/_vote_tweets.html.erb:2:in `_app_views_shared__vote_tweets_html_erb__2738953379660121418_70243350609340'
app/views/hashtags/create.js.erb:2:in `_app_views_hashtags_create_js_erb___1440072038737667206_70243345272440'
app/controllers/hashtags_controller.rb:23:in `create'
hashtag_controller
class HashtagsController < ApplicationController
def home
end
def vote
@random_hashtags = Hashtag.order("RANDOM()").limit(4)
end
def show
end
def index
end
def create
Hashtag.pull_hashtag(params[:hashtag])
@random_hashtag_pull = Hashtag.random_hashtags_pull
respond_to do |format|
format.html { redirect_to vote_path }
format.js
end
end
end
标签.rb
class Hashtag < ActiveRecord::Base
attr_accessible :text, :profile_image_url, :from_user, :created_at, :tweet_id, :hashtag, :from_user_name, :view_count
after_find :update_view_count
def self.pull_hashtag(hashtag)
dash = "#"
@hashtag_scrubbed = [dash, hashtag].join
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
)
end
end
end
def self.random_hashtags_pull
Hashtag.where{ |hashtag| hashtag.hashtag =~ @hashtag_scrubbed}.order{"RANDOM()"}.limit(4)
end
def update_view_count
count = (view_count + 1)
view_count = count
save!
end
end