Rails: How to pass a post's URL in an after_commit method

南笙酒味 提交于 2019-12-11 18:06:24

问题


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:

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

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"})

supportpost.rb

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

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

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


回答1:


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') 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.

I hope this helps.



来源:https://stackoverflow.com/questions/5684027/rails-how-to-pass-a-posts-url-in-an-after-commit-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!