Вставка переменной в маршруты - map.resources: posts,: as => X - это возможно? - PullRequest
2 голосов
/ 30 апреля 2010

Хорошо, я работаю над своего рода приложением для блога. Пока что он позволяет пользователю регистрироваться в своей учетной записи, создавать сообщения, теги, комментарии и т. Д.

Я только что реализовал возможность использовать www.myapp.com/brandon, чтобы установить @user для поиска по имени пользователя и, следовательно, правильно отображать информацию о пользователях по каждому URL. Поэтому, когда вы заходите на сайт www.myapp.com/brandon, вы видите все посты, теги и комментарии Брэндона, связанные с этими постами и т. Д. Отлично работает.

Я реализую это сопоставление URL-адресов через файл rout.rb, добавив следующее:

map.username_link '/:username', :controller => 'posts', :action => 'index'

А затем просто установите переменную @user в PostController и соответствующие представления для find_by_username. Теперь проблема заключается в следующем. Когда вы нажимаете на заголовок сообщения на странице www.myapp.com/brandon, он отправляется на myapp.com/posts/id без имени пользователя в URL.

Как мне указать rails заменить / posts на / username.

Можно ли даже вставить переменную user_username в этот код?

map.resources :posts, :as => [what goes here] 

Ответы [ 3 ]

4 голосов
/ 30 апреля 2010

Вы сказали, что на странице будет больше, чем просто posts? comments и tags тоже? Похоже, нам нужно некоторое объединение ресурсов здесь ...

Еще одна проблема: что если пользователь выберет имя faq, а вы захотите domain.com/faq в будущем? Вы не можете знать все URL, которые вам понадобятся в будущем. Добавление префиксов к путям /profiles - отличный способ создать небольшое «пространство имен», чтобы этого не происходило. Итак ...

Почему бы не ProfilesController?

script/generate controller profiles index show

routes.rb

ActionController::Routing::Routes.draw do |map|

  map.resources :profiles,        :only => [:index, :show] do |profile|
    profile.resources :posts,     :only => [:index, :show]
    profile.resources :comments,  :only => [:index, :show]
    profile.resources :tags,      :only => [:index, :show]
  end

  # ...
end

Это даст вам следующие маршруты

        profiles GET /profiles(.:format)                          {:controller=>"profiles", :action=>"index"}
         profile GET /profiles/:id(.:format)                      {:controller=>"profiles", :action=>"show"}
   profile_posts GET /profiles/:profile_id/posts(.:format)        {:controller=>"posts", :action=>"index"}
    profile_post GET /profiles/:profile_id/posts/:id(.:format)    {:controller=>"posts", :action=>"show"}
profile_comments GET /profiles/:profile_id/comments(.:format)     {:controller=>"comments", :action=>"index"}
 profile_comment GET /profiles/:profile_id/comments/:id(.:format) {:controller=>"comments", :action=>"show"}
    profile_tags GET /profiles/:profile_id/tags(.:format)         {:controller=>"tags", :action=>"index"}
     profile_tag GET /profiles/:profile_id/tags/:id(.:format)     {:controller=>"tags", :action=>"show"}

profiles_controller.rb

class ProfilesController < ApplicationController

  # show all profiles; profile browser
  # /profiles
  def index
  end

  # show one profile
  # /profiles/:id
  def show
    @user = User.find_by_username(params[:id])
  end

end

posts_controller.rb (и другие)

class PostsController < ApplicationController

  before_filter :find_profile, :only => [:index, :show]

  # list all posts for this profile
  # /profiles/:profile_id/posts
  def index
  end

  # show one post for this profile
  # /profiles/:profile_id/posts/:id
  def show
  end

  protected 

    def find_profile
      @user = User.find_by_username(params[:profile_id])
    end

end

0 голосов
/ 30 апреля 2010

Я не знаю много о маршрутах и ​​прочем, так что простите, если это не имеет смысла, но разве это не работает для вас?

map.resources :posts, :path_prefix => '/:username' do |post|
    post.resources :comments
end

Я вижу здесь, что это сгенерирует следующее

            posts GET    /:username/posts(.:format)                            {:controller=>"posts", :action=>"index"}
                  POST   /:username/posts(.:format)                            {:controller=>"posts", :action=>"create"}
         new_post GET    /:username/posts/new(.:format)                        {:controller=>"posts", :action=>"new"}
        edit_post GET    /:username/posts/:id/edit(.:format)                   {:controller=>"posts", :action=>"edit"}
             post GET    /:username/posts/:id(.:format)                        {:controller=>"posts", :action=>"show"}
                  PUT    /:username/posts/:id(.:format)                        {:controller=>"posts", :action=>"update"}
                  DELETE /:username/posts/:id(.:format)                        {:controller=>"posts", :action=>"destroy"}
    post_comments GET    /:username/posts/:post_id/comments(.:format)          {:controller=>"comments", :action=>"index"}
                  POST   /:username/posts/:post_id/comments(.:format)          {:controller=>"comments", :action=>"create"}
 new_post_comment GET    /:username/posts/:post_id/comments/new(.:format)      {:controller=>"comments", :action=>"new"}
edit_post_comment GET    /:username/posts/:post_id/comments/:id/edit(.:format) {:controller=>"comments", :action=>"edit"}
     post_comment GET    /:username/posts/:post_id/comments/:id(.:format)      {:controller=>"comments", :action=>"show"}
                  PUT    /:username/posts/:post_id/comments/:id(.:format)      {:controller=>"comments", :action=>"update"}
                  DELETE /:username/posts/:post_id/comments/:id(.:format)      {:controller=>"comments", :action=>"destroy"}
0 голосов
/ 30 апреля 2010

Вы можете создать ссылку, используя:

= link_to "User Posts", subdomain_link_url(@user.username, @post)

Тогда в вашем PostController я бы использовал before_filter для поиска и установки переменной @user:

class PostController < ApplicationController
  before_filter :find_user

  def other_method
    # Some code here
  end

protected
  def find_user
    @user = User.find_by_username(params[:username])
  end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...