Rails 3 - 基于显示静态页面的用户属性的虚荣URL

时间:2013-12-02 14:25:40

标签: ruby-on-rails

我想在我的rails app中实现虚荣网址。我的用户模型中有一个url属性。因此,当有人导航到mycoolapp.com/时,他们将被路由到静态页面,该页面将根据URL获取特定的用户信息并在页面上显示。我查看了虚荣URL的宝石,但我不确定这对我有用。现在我手动实现这个......

#config/routes
  get 'tommystavern', to: 'static_pages#tommystavern', as: 'tommystavern'

#app/controllers/static_pages_controller.rb
  def tommystavern
    @events = Event.find_all_by_user_id 2
  end

#app/views/static_pages/tommystavern.html.erb
<h1>Tommy's Tavern events</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Starts at</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @events.each do |event| %>
  <tr>
    <td><%= event.title %></td>
    <td><%= event.starts_at %></td>
    <td><%= event.description %></td>
  </tr>
<% end %>
</table>

我想在我的控制器中有一条“智能”路线,可以在我的User.url属性中找到该网址,然后将其发送到app / views / static_pages / home.html.erb这样的常规页面基于URL的用户事件。有任何想法吗?提前谢谢!

2 个答案:

答案 0 :(得分:0)

如果你在路线文件中使用你的用户怎么办:

User.all.each do |user|
  get user.url, to: 'static_pages#user_profile', :id => user.id
end

然后在你的控制器中:

def user_profile
  @user = User.find(params[:id])
  @events = Event.find_all_by_user_id @user.id
end

然后在你看来:

<h1><%= @user.name %> events</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Starts at</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

  <% @events.each do |event| %>
    <tr>
      <td><%= event.title %></td>
      <td><%= event.starts_at %></td>
      <td><%= event.description %></td>
    </tr>
  <% end %>
</table>

答案 1 :(得分:0)

这是有效的......在这里,我做的就是...

#config/routes.rb
  get '/:website', :controller => 'static_pages', :action => 'vanity'

#app/controllers/static_pages_controller.rb
  def vanity
      @user = User.find_by_website(params[:website])
    if @user != nil #in case someone puts in a bogus url I redirect to root
      @events = @user.events
    else
      redirect_to :root
    end
  end

#app/views/static_pages/vanity.html.erb
<h1><%= @user.website  %> events</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Starts at</th>
    <th>Description</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @events.each do |event| %>
  <tr>
    <td><%= event.title %></td>
    <td><%= event.starts_at %></td>
    <td><%= event.description %></td>
  </tr>
<% end %>
</table>