Rails:如何传递url参数?

时间:2011-04-16 19:36:25

标签: ruby-on-rails-3 activerecord parameters

我需要将每个帖子的url传递给用户模型,以便可以与twitter共享。现在我可以传递帖子的属性,例如标题和内容,这些属性是与twitter共享的,但我似乎无法弄清楚如何传递帖子网址。提前谢谢。

post.rb

after_commit :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

1 个答案:

答案 0 :(得分:1)

我没有尝试或测试过它,但我猜你可以这样做:

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

在此之前,在您的模型中添加以下内容:

include ActionController::UrlWriter

这将使您的模型中的url助手也可用。您可以阅读this以获取有关它的更多信息。

请尝试这一点(再次在this page上找到):

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

[编辑]

我刚读过你的gist,你应该做的是:

## 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

或者:

  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

非常重要的是,您在 share_all 方法中获取该网址而不是在其外部,因为无论是在内部还是外部,self都具有相同的值。当它在方法内部时,self引用调用share_all方法的Post实例。当它在外面时它就是Post类本身。

我已经测试了这两种变体并且效果很好:)。