Abel Toy
Abel Toy

Reputation: 328

Rails named has_many with a limit

I want to achieve a has_many association with a x number of records, and the records would be named.

Let's explain that better. In a previous question I asked how to make a text area with a selectable markup language and we reached the conclusion that I needed a separate model, Field which had the multiple fields I needed (language, original and rendered).

Now I want to be able to make a model, let's say User, which had two of these fields. For example: about_me and biography. How would I create those fields every time I create the user, edit them when I edit the user and destroy them when I edit the user? And how would I display them simply writing: User.about_me and User.biography?

Thanks in advance for the answer.

Upvotes: 0

Views: 416

Answers (2)

apneadiving
apneadiving

Reputation: 115521

David's solution creates the joint model.

Then you have to include the form of the profile in the User form. You'll have to use accepts_nested_attributes_for method in the User model.

To destroy the profile when user is deleted, add dependent => :destroy to the relationship between the 2 models.

Upvotes: 1

David Sulc
David Sulc

Reputation: 25994

You'll need to use callbacks (http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html).

For example, in your User model, have a after_create callback that will create the requisite fields.

Also,have an after_save callback that checks user.changed? and if it is different, update the fields.

Upvotes: 1

Related Questions