簡體   English   中英

Rails 3-基於顯示靜態頁面的用戶屬性的Vanity URL

[英]Rails 3 - Vanity URL based on user attribute that displays a static page

我想在我的rails應用程序中實現虛榮網址。 我的用戶模型中有一個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屬性中找到該URL,然后將其發送到諸如app / views / static_pages / home.html.erb這樣的常規頁面,該頁面將顯示基於在網址上。 有任何想法嗎? 提前致謝!

如果要像這樣在路由文件中使用“用戶”,該怎么辦:

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>

那行得通...同時,這是我所做的...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM