【发布时间】:2011-08-06 15:25:52
【问题描述】:
我正在尝试使用 after_commit 方法将参数从帖子传递到用户模型,然后通过另一种方法将其共享到 twitter。
当我从帖子模型中传递一些东西,比如“标题”或“内容”时,它工作得很好:
post.rb
after_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: syntax error, unexpected keyword_self, expecting ')' def twitter_share(self)
并将其发布到 twitter #
我的问题是如何正确设置传递 'self' 以便可以使用 twitter.update() 调用任何参数?
另外,您如何提取帖子的 URL,以便您可以传递 URL 以在 twitter 上分享?
编辑:
尝试 Rails.application.routes.url_helpers.post_url(@post, :host => 'myhost.com')
在 post.rb 中
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:in `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
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord parameter-passing