has_many models in a form

Hi, guys. There are four models in the program, A has_many B through C, B has_many A through C, A has_many D, D belongs_to A. I have a form to create A. Inspired by Ryan Bates' railscasts I was able to create A and D in the same form, and link A to B(created beforehand) through C in the same form as well. Is it possible to create A and B in the same form? Thanks in advance.

Hi, guys.

There are four models in the program, A has_many B through C, B has_many

A through C, A has_many D, D belongs_to A. I have a form to create A.

Inspired by Ryan Bates’ railscasts I was able to create A and D in the

same form, and link A to B(created beforehand) through C in the same

form as well. Is it possible to create A and B in the same form?

Thanks in advance.

Ichiro, it might have been better to provide the sample code as follows:

class A < AR

has_many :B, :through => :C

has_many :smiley:

end

class B < AR

has_many :A, :through => :C

end

class D < AR

belongs_to :A

end

Next, you should be able to create A and B in the same form using

accepts_nested_attributes_for. For example,

class A < AR

has_many :B, :through => :C

has_many :smiley:

accepts_nested_attributes_for :B

end

Note: You’ll need to create the appropriate form as Ryan Bates walks

you through in his nested model form screencasts.

Good luck,

-Conrad

Thank you for your help, Conrad. I'll try it out later. You are right, I should've provided the sample code. It's cleaner and more clear.

Conrad Taylor wrote: Ichiro, it might have been better to provide the sample code as follows:

class A < AR    has_many :B, :through => :C    has_many :smiley: end

class B < AR   has_many :A, :through => :C end

class D < AR    belongs_to :A end

Next, you should be able to create A and B in the same form using accepts_nested_attributes_for. For example,

class A < AR    has_many :B, :through => :C    has_many :smiley:    accepts_nested_attributes_for :B end

Note: You'll need to create the appropriate form as Ryan Bates walks you through in his nested model form screencasts.

Good luck,

-Conrad

--

I don't know if I need to write a new post, but the issue is related to the topic. I did what Conrad suggested and it worked perfectly. But there's a problem on deleting B on the edit page of A. Here's the A.rb:

class A < AR     has_many :B, :through => :C     has_many :smiley:     accepts_nested_attributes_for :B, :allow_destroy=>true end

When I deleted B on the edit page, B was gone, but it's also deleted from table B. What I want is disassociate B from A and keep B in its table when I do the delete. Is there a way to do it?

Another problem is when I add B to A, if B already exists in table B, can I link to B instead of creating a duplicate one in table B? Thanks.