0

I have a memberships resource and it belongs to user and club. I want to access the parent attributes i.e for club and user and I read that accepts_nested_attributes_for is used for parent side of a relationship. What should I write in my membership model?

I have searched about it both in stackoverflow and activeadmin docs but I did not get a thorough explanation about solving my problem...

My membership model is: membership.rb

class Membership < ApplicationRecord
    require 'csv'
    belongs_to :club
    belongs_to :user
end

Also what should i write in my membership resource which I have already registered with AA...

Pujan Soni
  • 155
  • 13
  • did you check this https://stackoverflow.com/questions/13506735/rails-has-many-through-nested-form ? – S R Dec 27 '18 at 06:37

2 Answers2

0

You can mention the following :- 1) has_many: memberships #in user model 2) has_many: memberships #in club model

This will help you access parent attributes from child model :- membership.user, membership.club

Also, you can mention accepts_nested_attributes_for: memberships in user model. When you write this, you can then build a common form for user and membership and modify both of them simultaneously. To achieve this, you will have to allow membership attributes in users_controller.rb.

Ankur Shukla
  • 345
  • 2
  • 9
0

The following should work(Similar question):

class Club < ApplicationRecord
   has_many :memberships, :dependent => :destroy 
   has_many :users, :through => :memberships
   accepts_nested_attributes_for :membership 
end

class User < ApplicationRecord
   has_many :memberships, :dependent => :destroy 
   has_many :clubs, :through => :memberships
   accepts_nested_attributes_for :membership 
end

class Membership < ApplicationRecord
    require 'csv'
    belongs_to :club
    belongs_to :user
    accepts_nested_attributes_for :club
end
S R
  • 674
  • 2
  • 18
  • 45