Rails:如何在 after_commit 方法中传递帖子的 URL [英] Rails: How to pass a post's URL in an after_commit method

查看:60
本文介绍了Rails:如何在 after_commit 方法中传递帖子的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在弄清楚如何为每个用户帖子(在我的应用中称为支持帖子)创建一个 url 并将其传递给 after_commit 方法时遇到了一些真正的麻烦.现在我可以传递支持帖子的属性,例如标题和内容,这些属性会共享到推特:

I'm having some real troubles figuring out how to create a url for each user post (called supportposts in my app) and pass it to an after_commit method. Right now I can pass attributes of the supportpost, such as title and content, which is shared to twitter:

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}")           #<--- this goes to twitter feed 
end

现在我真正想做的是将支持帖子的 URL 共享到 Twitter 提要中.我正在尝试像这样访问模型外部的 url 助手,但它弄乱了我的路线,并且出现了 RoutingError (没有路线匹配 {:action=>"destroy", :controller=>"supportposts"})

Now what I really want to do is share the supportpost's URL into the twitter feed. I'm trying to access url helpers outside the model like this but it messes up my routes and I get a RoutingError (No route matches {:action=>"destroy", :controller=>"supportposts"})

after_commit :share_all

Rails.application.routes.url_helpers.supportpost_url(@supportpost, :host => 'examplehost.com') 

def share_all
if user.authentications.where(:provider => 'twitter').any?
 user.twitter_share(supportpost_url)
 end
end

我在这里做错了什么?如何将 URL 正确传递到 twitter_share?

What am I doing wrong here? How can I properly pass the URL into twitter_share?

这里是我的路由和支持控制器/模型 http://pastie.org/1799492

Here my routes and suppostpost controller/model http://pastie.org/1799492

推荐答案

def share_all
  if user.authentications.where(:provider => 'twitter').any?
    supportpost_url = Rails.application.routes.url_helpers.url_for :action => :show, :controller => 'supportposts', :id => self, :host => 'example.com'
    user.twitter_share(supportpost_url)
  end
end

Rails.application.routes.url_helpers.supportpost_url(@supportpost, :host => 'examplehost.com') 你拥有它不会有任何好处.哦,顺便说一下,我在这个例子中使用了 url_for() 但是你可能也可以像你在上面的问题中那样使用 supportpost_url() .这里最重要的是你在哪里调用方法.

Rails.application.routes.url_helpers.supportpost_url(@supportpost, :host => 'examplehost.com') where you have it isn't going to do any good. Oh, and by the way, I used url_for() in this example but you could probably just as well use supportpost_url() like you did in the question above. The main thing here is where you are calling the method.

我希望这会有所帮助.

这篇关于Rails:如何在 after_commit 方法中传递帖子的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆