gpt4 book ai didi

ruby-on-rails - 解析@username 的帖子

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:22 25 4
gpt4 key购买 nike

我已经建立了一个类似于 Twitter 的@replies,允许用户通过用户日报相互联系......类似于 stackoverflow 的。

以此为指导 https://github.com/kltcalamay/sample_app/compare/original-version...master

我如何解析/扫描帖子,然后用指向该用户页面的链接替换@usernames

帖子示例。

Kevins Post:
@Pzpcreations @john @steve hey everyone lets all hang out today

我想扫描/解析帖子,然后将用户@Pzpcreations @john @steve 链接到他们的个人资料

我尝试在我的 Dailypost 模型中创建一个方法,将用户名存储在一个数组中....但我不知道如何替换它们并将它们链接到适当的用户页面

def username_link
str = self.content_html
recipient = str.scan(USERNAME_REGEX)
end

这给了我 ["@Pzpcreations", "@john", "@steve"]

请帮帮我....刚接触 rails :)

模型

class Recipient < ActiveRecord::Base
attr_accessible :dailypost_id, :user_id

belongs_to :user
belongs_to :dailypost

end

class User < ActiveRecord::Base
attr_accessible :name, :email, username

has_many :dailyposts, dependent: :destroy

has_many :replies, :class_name => 'Recipient', :dependent => :destroy
has_many :received_replies, :through => :replies, :source => 'dailypost'

end

class Dailypost < ActiveRecord::Base
attr_accessible :content, :recipients
belongs_to :user

###What is the Correct REGEX for Rails 4?
USERNAME_REGEX = /@\w+/i

has_many :recipients, dependent: :destroy
has_many :replied_users, :through => :recipients, :source => "user"

after_save :save_recipients

**private**

def save_recipients
return unless reply?

people_replied.each do |user|
Recipient.create!(:dailypost_id => self.id, :user_id => user.id)
end
end

def reply?
self.content.match( USERNAME_REGEX )
end

def people_replied
users = []
self.content.clone.gsub!( USERNAME_REGEX ).each do |username|
user = User.find_by_username(username[1..-1])
users << user if user
end
users.uniq
end
end

架构

create_table "recipients", :force => true do |t|
t.string "user_id"
t.string "dailypost_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end

[#<Recipient id: 7, **user_id: "103"**, dailypost_id: "316", created_at: "2013-06-18
10:31:16", updated_at: "2013-06-18 10:31:16">]

User_ID in recipients are the users that are mentioned in the Dailypost.

观点

<%= link_to dailypost.username_link %>

最佳答案

您可以将每个匹配传递给一个 block 。在此 block 中,您返回所需的链接,例如

def username_link
str = self.content_html
str.gsub!(USERNAME_REGEX).each do |recipient|
if User.find_by_name(recipient)
"[link to #{recipient}]"
else
recipient
end
end
end

编辑

app/helpers/posts_helper.rb 中创建一个辅助函数

def post_with_links(post)
post.content_html.gsub(/@\w+/).each do |username|
user = User.find_by_username(username[1..-1])
if user
link_to username, user
else
username
end
end

在你的 View 中使用它

<%= post_with_links(post) %>

关于ruby-on-rails - 解析@username 的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17222033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com