加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 设计:用户所属组织

发布时间:2020-12-17 03:29:53 所属栏目:百科 来源:网络整理
导读:我正在使用设计进行身份验证,在“注册”页面上,我有一个“组织”文本字段,因此当用户注册时,他们将创建一个组织,我希望用户与该组织相关联(用户模型具有organization_id属性).我创建了设计视图,并为组织名称添加了fields_for.在我的模型中,我有User belongs_
我正在使用设计进行身份验证,在“注册”页面上,我有一个“组织”文本字段,因此当用户注册时,他们将创建一个组织,我希望用户与该组织相关联(用户模型具有organization_id属性).我创建了设计视图,并为组织名称添加了fields_for.在我的模型中,我有User belongs_to:organization and Organization has_many:users(将有多个用户与组织关联).在没有修改控制器的情况下,我已经找不到尝试这样做的每一条路,但没有运气.请不要在不修改控制器的情况下建议这样做,除非你有一个示例应用程序,你已经实现了它,你可以指向它.

我已经创建了一个注册控制器,如下所示:Override devise registrations controller

我只是在控制器中抛出了一些put语句,我没有看到它们显示在控制台上,所以看起来我没有进入这个控制器.

我还将我的观点从app / view / devise / registrations复制到app / views / registrations,之后我的观点似乎来自外太空!我创建的组织字段不再显示,我似乎无法分辨加载视图的位置.

很抱歉没有更简洁,但我不知道该去哪里.

解决方法

您可以在用户模型中使用accepts_nested_attributes_for( documentation)

它应该看起来像:

class User < ActiveRecord::Base
  belongs_to :organization
  accepts_nested_attributes_for :organization
end

class Organization < ActiveRecord::Base
  has_many :users
end

在视图中,您可以使用Rails帮助程序或手动创建字段:

<input type="text" name="user[organization_attributes][name]">

<% user = User.new(organization => Organization.new) %>
<%= form_for user do |form| %>
  <%= form.fields_for user.organization do |organization_form| %>
    <%= organization_form.text_field :name %>
  <% end %>
<% end %>

编辑:
您的设计视图应如下所示:

<h2>Sign up</h2>
<% resource.organization ||= Organization.new %>
<%= form_for(resource,:as => resource_name,:url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
  <div><%= f.label :email %><br />
  <%= f.email_field :email %></div>

  <%= f.fields_for resource.organization do |organization_form| %> 
    <div><%= organization_form.label :name %><br />
    <%= organization_form.text_field :name %></div>
  <% end %>

  <div><%= f.label :password %><br />
  <%= f.password_field :password %></div>
  <div><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation %></div>
  <div><%= f.submit "Sign up" %></div>
<% end %>
<%= render :partial => "devise/shared/links" %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读