Creating nested models - Rails 3.1

試著忘記壹切 提交于 2019-12-02 03:54:26

In a nutshell:

in your models

class UserEntity < ActiveRecord::Base
  has_many :users
  accepts_nested_attributes_for :users
end

class User < ActiveRecord::Base
  belongs_to :user_entity
  has_many   :user_login_services, :dependent => :destroy
  accepts_nested_attributes_for :user_login_services
end

class UserLoginService < ActiveRecord::Base
  belongs_to :user
  validates :user_id, :presence => true
end

in your controllers

def create
  @user_entity = UserEntity.new(params[:user_entity])
  @user_entity.save
  # To Do: handle redirections on error and success
end

and in your form

<%= form_for(@user_entity) do |f| %>
  <%= f.fields_for :users do |u| %>
    <%= u.fields_for :user_login_services do |ul| %>
      <%= ul.select :user_id, @user_entity.users.collect{|u| [u.name, u.id]} %>
    <% end %>
  <% end %>
<% end %>

Additionally I recommend you check out: http://railscasts.com/episodes/196-nested-model-form-part-1

You need to have accepts_nested_attributes_for and inverse_of relations defined.

class UserEntity < ActiveRecord::Base
  has_many   :users, :dependent => :restrict, :autosave => true, :inverse_of => :users_entity
  accepts_nested_attributes_for :users
end

class User < ActiveRecord::Base
  has_many    :user_login_services, :dependent => :destroy, :autosave => true, :inverse_of => :user
  belongs_to  :user_entity, :inverse_of => :users
  accepts_nested_attributes_for :user_login_services
end

class UserLoginService < ActiveRecord::Base
  belongs_to :user, :inverse_of => :users_login_services
  validates :user, :presence => true 
end

I also switched validates :user_id to validates :user assuming you want to validate the existence of the associated user and not just that the UserLoginService has a user_id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!