0

我正在使用设计进行身份验证,并使用户与建筑物相关联。我可以创建与正确建筑物适当关联的新用户,但如果新用户没有所有必需的输入,我会设计验证中断。

编码:

应用程序/模型/user.rb

class User < ActiveRecord::Base
  belongs_to :building
  attr_accessible :building_id
  ...
end

(我知道拥有 building_id attr_accessible 并不理想,但我不确定如何在不使用新用户注册表单中的 building_id 隐藏字段的情况下创建关联......)

class Building < ActiveRecord::Base
  has_many :users
  ...
end

在我的路线中,用户注册嵌套在建筑物内:

devise_for :users, controllers: { :registrations => "registrations" }, skip: [:registrations]

resources :users, except: [:new, :create] do
  resource :approvals, only: [:update]
end

match '/:building', to: "buildings#landing"
resources :buildings, except: [:new, :create, :destroy] do
  as :user do
    get '/signup' => 'registrations#new', as: :new_user_registration
    post '/signup' => 'registrations#create', as: :user_registration
  end
  ...
end

app/views/devise/registrations/new.html.erb

<%= simple_form_for(resource, :as => resource_name, :url => building_user_registration_path(), :html => {:class => 'form-inline', :multipart => true }) do |f| %>

    <%= render 'fields', f: f %>

  <div class="inputs">
    <%= f.input :role, collection: User::ROLES.collect %>
    <%= f.input :password, :required => true %>
    <%= f.input :password_confirmation, :required => true %>
  </div>

  <div class="actions">
    <%= f.button :submit, "Create my account", class: "btn btn-large btn-primary" %>
  </div>
<% end %>

然后,最后,app/views/devise/registrations/_fields.html.erb 中有问题的代码行

...
 <%= f.hidden_field :building_id, value: @building.id %>
...

如果正确填写了新用户的所有必填字段,则会创建与正确建筑物适当关联的新用户。如果任何必填字段为空白或无效,Devise 将在浏览器中引发以下错误:

RuntimeError in Registrations#create

Showing .../app/views/devise/registrations/_fields.html.erb where line #7 raised:

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id

第 7 行是:<%= f.hidden_field :building_id, value: @building.id %>

任何想法将不胜感激。我确定我在这里做了几件次优的事情......

4

2 回答 2

3

你可以做

<%= f.hidden_field :building_id, value: @building.try(:id) %>

@building但如果没有设置,我宁愿不包括这个字段

于 2013-06-22T20:19:45.090 回答
1

我在朋友的帮助下成功了。我已经有一个自定义注册控制器(在我的路线中提到),我添加了一个前置过滤器来查找建筑物:

class RegistrationsController < Devise::RegistrationsController

  before_filter :find_building, only: [:new, :create]

  ...

  private

  def find_building
    @building = Building.find_by_slug(params[:building_id])
  end

end
于 2013-06-29T15:43:53.393 回答