开发者

Rails: how to pass a url parameter?

I need to pass the url for each post into user model so it can be shared to twitter. Right now I can pass attributes of the post, such as title and content, which is shared to twitter, but I can't seem to figure out how to pass the post url. Thanks in advance.

post.rb

after_commit :开发者_Python百科share_all

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

user.rb

def twitter_share(post) 
 twitter.update("#{post.title}, #{post.content}")           #<--- this goes to twitter feed 
end


I haven't tried or tested it but I guess you can do something like:

def share_all
 if user.authentications.where(:provider => 'twitter').any?
  user.twitter_share(title, content, post_url(self, :host => "your_host"))
 end
end

Prior to that, in your model add this:

include ActionController::UrlWriter

This will make the url helper available in your model as well. You can read this to get more information about it.

Please try this as well (found it on this page again):

Rails.application.routes.url_helpers.post_url(self, :host => "your_host")

[EDIT]

I have just read your gist, what you should do is this instead:

## posts.rb
  after_commit :share_all
  def share_all
     # note that I am using self inside the method not outside it.
     url =  Rails.application.routes.url_helpers.post_url(self, :host => "localhost:3000")
     if user.authentications.where(:provider => 'twitter').any?
        user.twitter_share(url)  
    end
  end

Or:

  include ActionController::UrlWriter #very important if you use post_url(..) directly
  after_commit :share_all
  def share_all
     # if you use the url helper directly you need to include ActionController::UrlWriter
     url =  post_url(self, :host => "localhost:3000")
     if user.authentications.where(:provider => 'twitter').any?
        user.twitter_share(url)  
    end
  end

It is very important that you get that url inside the share_all method and not outside it, because self has not the same value whether it's inside or outside. When it's inside the method, self references the instance of Post on which the share_all method is called. When it's outside it's the class Post itself.

I have tested those two variants and they work just well :).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜