Rails:如何传递 url 参数?
我需要将每个帖子的 url 传递到用户模型中,以便可以将其共享到 Twitter。现在我可以传递帖子的属性,例如标题和内容,这些属性会共享到 Twitter,但我似乎不知道如何传递帖子网址。提前致谢。
帖子.rb
after_commit :share_all
def share_all
if user.authentications.where(:provider => 'twitter').any?
user.twitter_share(self)
end
end
用户.rb
def twitter_share(post)
twitter.update("#{post.title}, #{post.content}") #<--- this goes to twitter feed
end
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 :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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我还没有尝试或测试过它,但我想你可以这样做:
在此之前,在你的模型中添加以下内容:
这将使 url 帮助器在你的模型中也可用。您可以阅读此来获取有关它的更多信息。
请也尝试一下(在这个上找到它再次页面):
[编辑]
我刚刚阅读了您的要点,您应该做什么是这个:
或者:
在 share_all 方法内部而不是外部获取该 url 非常重要,因为无论是内部还是外部, self 的值都不一样。当它位于方法内部时, self 引用调用 share_all 方法的 Post 实例。当它在外部时,它是类 Post 本身。
我已经测试了这两个变体,它们工作得很好:)。
I haven't tried or tested it but I guess you can do something like:
Prior to that, in your model add this:
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):
[EDIT]
I have just read your gist, what you should do is this instead:
Or:
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 :).