Rails: ресурс и формы - PullRequest
       23

Rails: ресурс и формы

1 голос
/ 13 июля 2011

Предисловие: я не уверен, что ресурсы.

Мне нужна эта форма (которая работает по маршруту user/sign_up) для работы на моей «автономной странице», чтобы пользователи могли по-прежнему регистрироваться, когда мое приложение не работает. Мой application_controller вызывает :filter_before, :except => [:offline], а мой registrations_controller выполняет действие :skip_filter_before. (Это называется действием?)

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <p><%= f.label :email %><br />
  <%= f.email_field :email %></p>
  <p><%= f.submit "Sign up" %></p>
<% end %>

Мой регистрационный_контроллер:

class RegistrationsController < Devise::RegistrationsController
  before_filter :get_teams
  skip_filter :require_online
  def create
    build_resource

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        respond_with resource, :location => redirect_location(resource_name, resource)
      else
        set_flash_message :notice, :inactive_signed_up, :reason => resource.inactive_message.to_s if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords(resource)
      respond_with_navigational(resource) { render_with_scope :new }
    end
  end
  ...
end

Маршруты:

         confirm_account        /confirm_account(.:format)                {:controller=>"confirmations", :action=>"confirm_account"}
                 sign_up        /sign_up(.:format)                        {:action=>"sign_up", :controller=>"user/sign_up"}
        new_user_session GET    /user/sign_in(.:format)                   {:action=>"new", :controller=>"devise/sessions"}
            user_session POST   /user/sign_in(.:format)                   {:action=>"create", :controller=>"devise/sessions"}
    destroy_user_session GET    /user/sign_out(.:format)                  {:action=>"destroy", :controller=>"devise/sessions"}
           user_password POST   /user/password(.:format)                  {:action=>"create", :controller=>"devise/passwords"}
       new_user_password GET    /user/password/new(.:format)              {:action=>"new", :controller=>"devise/passwords"}
      edit_user_password GET    /user/password/edit(.:format)             {:action=>"edit", :controller=>"devise/passwords"}
                         PUT    /user/password(.:format)                  {:action=>"update", :controller=>"devise/passwords"}
cancel_user_registration GET    /user/cancel(.:format)                    {:action=>"cancel", :controller=>"registrations"}
       user_registration POST   /user(.:format)                           {:action=>"create", :controller=>"registrations"}
   new_user_registration GET    /user/sign_up(.:format)                   {:action=>"new", :controller=>"registrations"}
  edit_user_registration GET    /user/edit(.:format)                      {:action=>"edit", :controller=>"registrations"}
                         PUT    /user(.:format)                           {:action=>"update", :controller=>"registrations"}
                         DELETE /user(.:format)                           {:action=>"destroy", :controller=>"registrations"}
       user_confirmation POST   /user/confirmation(.:format)              {:action=>"create", :controller=>"confirmations"}
   new_user_confirmation GET    /user/confirmation/new(.:format)          {:action=>"new", :controller=>"confirmations"}
                         GET    /user/confirmation(.:format)              {:action=>"show", :controller=>"confirmations"}
             user_unlock POST   /user/unlock(.:format)                    {:action=>"create", :controller=>"devise/unlocks"}
         new_user_unlock GET    /user/unlock/new(.:format)                {:action=>"new", :controller=>"devise/unlocks"}
                         GET    /user/unlock(.:format)                    {:action=>"show", :controller=>"devise/unlocks"}
        editreject_admin GET    /admin/:id/editreject(.:format)           {:action=>"editreject", :controller=>"admin"}
            reject_admin GET    /admin/:id/reject(.:format)               {:action=>"reject", :controller=>"admin"}
            accept_admin GET    /admin/:id/accept(.:format)               {:action=>"accept", :controller=>"admin"}
     entries_admin_index GET    /admin/entries(.:format)                  {:action=>"entries", :controller=>"admin"}
 preferences_admin_index GET    /admin/preferences(.:format)              {:action=>"preferences", :controller=>"admin"}
             admin_index GET    /admin(.:format)                          {:action=>"index", :controller=>"admin"}
           about_entries GET    /entries/about(.:format)                  {:action=>"about", :controller=>"entries"}
             all_entries GET    /entries/all(.:format)                    {:action=>"all", :controller=>"entries"}
       myentries_entries GET    /entries/myentries(.:format)              {:action=>"myentries", :controller=>"entries"}
              rate_entry GET    /entries/:id/rate(.:format)               {:action=>"rate", :controller=>"entries"}
            submit_entry PUT    /entries/:id/submit(.:format)             {:action=>"submit", :controller=>"entries"}
          entry_comments POST   /entries/:entry_id/comments(.:format)     {:action=>"create", :controller=>"comments"}
           entry_comment DELETE /entries/:entry_id/comments/:id(.:format) {:action=>"destroy", :controller=>"comments"}
                 entries GET    /entries(.:format)                        {:action=>"index", :controller=>"entries"}
                         POST   /entries(.:format)                        {:action=>"create", :controller=>"entries"}
               new_entry GET    /entries/new(.:format)                    {:action=>"new", :controller=>"entries"}
              edit_entry GET    /entries/:id/edit(.:format)               {:action=>"edit", :controller=>"entries"}
                   entry GET    /entries/:id(.:format)                    {:action=>"show", :controller=>"entries"}
                         PUT    /entries/:id(.:format)                    {:action=>"update", :controller=>"entries"}
                         DELETE /entries/:id(.:format)                    {:action=>"destroy", :controller=>"entries"}
                                /auth/:service/callback(.:format)         {:controller=>"services", :action=>"create"}
                services GET    /services(.:format)                       {:action=>"index", :controller=>"services"}
                         POST   /services(.:format)                       {:action=>"create", :controller=>"services"}
                    root        /(.:format)                               {:controller=>"entries", :action=>"index"}
               countdown        /countdown(.:format)                      {:controller=>"application", :action=>"countdown"}

Ответы [ 2 ]

1 голос
/ 21 июля 2011

«Ресурс» в случае Devise - это то, что фактически регистрируется.В вашем случае это скорее всего пользователь.Тем не менее, пользователь не жестко закодирован в Devise, так что вы можете иметь несколько типов пользователей, например, администраторы или редакторы.Для простоты в данном случае, когда вы читаете «ресурс», подумайте «пользователь».

Остальная часть моего ответа на самом деле не является ответом, просто запрос дополнительной информации.Я отредактирую это с правильным ответом, если смогу помочь:)

Что касается вашего вопроса, я не уверен на 100%, что я понимаю, что выспрашивать о.Вы пытаетесь показать форму регистрации на автономной странице или пытаетесь отправить регистрационные данные на автономную страницу?В любом случае, вы получаете и ошибки или что-то подобное мешает вам сделать это?Если да, пожалуйста, опубликуйте сообщение об ошибке или подробности неожиданного поведения.Также может быть полезно опубликовать ваш route.rb, в зависимости от того, в чем ваша проблема.

Еще одна вещь, с которой мне неясно, является частью автономной страницы вашего приложения rails или размещена в другом месте?Если приложение не работает, оно не будет доступно.

Обновление:

Итак, насколько я понимаю, вы пытаетесь поместить форму регистрации пользователя наавтономная страница?Если это так, попробуйте это.

В вашем контроллере:

def offline
  @user = User.new
end

В вашем представлении offline.html.erb:

    <%= form_for(@user, :url => user_registration_path) do |f| %>
      <%= devise_error_messages! %>

      <p><%= f.label :email %><br />
      <%= f.email_field :email %></p>
      <p><%= f.submit "Sign up" %></p>
    <% end %>

Я не думаю, что у вас естьмаршрут, настроенный для вашего автономного действия, так что вам нужно будет это сделать.Для быстрого и простого способа используйте что-то вроде этого:

match '/offline' => "welcome#offline"

Где welcome - имя контроллера, на котором находится ваше автономное действие.

Помогает ли это?

0 голосов
/ 14 июля 2011

Это будет зависеть от того, как настроено registration_path, что-то, что вы определили в своих маршрутах, но не объяснили здесь.

Также проверьте вывод rake routes, чтобы увидеть, как он интерпретируется в вашей среде. Было бы целесообразно проверить log/development.log, чтобы увидеть, как обрабатывается отправка формы, как показано интерпретированное params.

Что такое resource, это исходит от Devise или вашего приложения?

...