Creating nested models - Rails 3.1

后端 未结 2 725
南笙
南笙 2021-01-23 19:02

I am trying to create 3 nested models at once, and have trouble with my validations.

These are my models:

class UserEntity < ActiveRecord::Base
  ha         


        
相关标签:
2条回答
  • 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

    0 讨论(0)
  • 2021-01-23 19:45

    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.

    0 讨论(0)
提交回复
热议问题