0

在我的 Rails 应用程序中,我有一个带有 url_field 用于 Twitter 的用户模型(设计)。

现在我的显示页面中有这个:

<%= link_to @deal.user.company_twitter, @deal.user.company_twitter, :class => "comp_twitter" %>

它在显示页面中显示整个链接(甚至http://),这是因为我的 url_field 使用户添加“http://”,否则它不会验证链接。

我希望用户在创建个人资料时只添加他们的“@name”而不是整个 Twitter 链接。我还想在“显示”页面中只显示@name 而不是 Twitter 链接。我怎样才能做到这一点?

4

1 回答 1

1

Simply don't use an url_field, but a regular string database field, like twitter_username. When signing up, let the user enter their username, e.g. foo.

For getting the real URL to the Twitter account, create a new method in your user.rb model:

def twitter_url
  "http://twitter.com/#{self.twitter_username}"
end

The advantage is that at this point, in your model, you can include a custom validation that would check if this URL really exists after the user has submitted their twitter_username.

Finally, use that in your view instead of just the URL:

<%= link_to "@#{@user.twitter_username}", @user.twitter_url %>

This would render:

<a href="http://twitter.com/foo">@foo</a>
于 2012-08-05T21:06:29.957 回答