如何解决Rails:如何使用after_commit方法从模型传递参数,最终在Twitter上共享
| 我正在尝试使用after_commit方法将参数从帖子传递到用户模型,并在其中与另一种方法共享给Twitter。 当我只是从帖子模型传递诸如\'title \'或\'content \'之类的东西时,它就可以正常工作: post.rbafter_commit :share_all
def share_all
if user.authentications.where(:provider => \'twitter\').any?
user.twitter_share(title,content)
end
end
user.rb
def twitter_share(title,content)
twitter.update(\"#{title},#{content}\")
end
但是据我所知,我在其他地方读到我可以通过\'self \'代替\'title \'和\'content \',但仍然可以使用\'title \'和\'content \'以及模型中的其他任何内容,例如\'created_at \'。但是,我似乎无法正常工作,我已经尝试过:
post.rb
def share_all
if user.authentications.where(:provider => \'twitter\').any?
user.twitter_share(self)
end
end
user.rb
def twitter_share(self)
twitter.update(\"#{title},#{content}\")
end
而且我得到SyntaxError(/Users/ihal/Desktop/dayor/app/models/user.rb:118:语法错误,意外的keyword_self,期望\')\'
def twitter_share(个体)
并将其发布到Twitter# class Post < ActiveRecord::Base # line 19
after_commit :share_all
Rails.application.routes.url_helpers.post_url(@post,:host => \'myhost.com\') #line 37
def share_all
if user.authentications.where(:provider => \'twitter\').any?
user.twitter_share(self)
end
end
当我删除帖子时,出现错误:
在2011-04-15 14:57:17 -0700为127.0.0.1开始发布POST \“ / posts / 32 \”
由PostsController#destroy处理为HTML
参数:{\“ authenticity_token \” => \“ x8KkqLLCLdTOouUfCMzyWWmwxLIKThnE1n3rQNSkew8 = \”,\“ id \” => \“ 32 \”}
用户负载(1.1ms)SELECT \“ users \”。* FROM \“ users \” WHERE(\“ users \”。\“ id \” = 5)LIMIT 1
82ms完成
ActionController :: RoutingError(没有路由匹配{:action => \“ destroy \”,:controller => \“ posts \”}):
app / models / post.rb:37:in<class:Post>\'
app/models/post.rb:19:in
\'
app / controllers / posts_controller.rb:36:在“ authorized_user \”中
在营救/布局中渲染/Users/ihal/.rvm/gems/ruby-1.9.2-p136@rails3gemset/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.erb(1.2ms)
后控制器
def destroy
@post.destroy
redirect_to root_path
end
private
def authorized_user
@post = Post.find(params[:id]) #line 36
redirect_to root_path unless current_user?(@spost.user)
end
end
解决方法
我在代码中看到的是,标题和内容是Post的属性。因此将它们作为他们的名字传递时,将转换为它们的值。
现在您从post通过twitter_share传递self,那么post对象将传递给该方法。您需要按以下方式修改twitter_share方法以使其起作用
def twitter_share(post)
twitter.update(\"#{post.title},#{post.content}\")
end
,您是否考虑过使用观察者?这样,您可以将after_commit内容(似乎不属于模型)保留在适当的位置。另外,它有助于简化模型,而不会造成混乱。
对于语法错误,self
是保留字。在方法声明中重命名变量名称。因此,尝试类似:
def twitter_share(post)
# do stuff
end
要访问控制器外部的url帮助器,请使用:
Rails.application.routes.url_helpers.post_url(@post,:host => \'myhost.com\')
在控制器外部访问url辅助程序时,请不要忘记使用:host选项,以便该辅助程序具有上下文。
,def twitter_share(post)
twitter.update(\"#{post.title},#{post.content}\")
end
您正在将一个Post传递到user.twitter_share方法中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。