Reputation: 6394
I did a search about this, and any kind of "Rails relationships" query a lot options, but I could not find my kind of case..
Can you please suggest the best way to implement this kind of relationships..
Parent can create Connection for his Kid.
I currently have three models - Parent, Kid and Connection (for storing data about Kid's connections)..
Parent:
has_many :kids
Kid:
belongs_to :parent
has_many :connections, :foreign_key => "connector_id"
has_many :connected_to, :through => :connections, :source => :connected
Connection:
attr_accessible :connected_id
belongs_to :connector, :class_name => "Kid"
belongs_to :connected, :class_name => "Kid"
Parent is able to create Kids.. I am struggling with the best way to teach Parent to create Connections* for his Kids..
Any suggestions are really appreciated..
UPDATE:
After looking into the advice by cug, I have the following:
in Parent: has_many :kids
def add_kid_connection(new_kid)
kids.each do |kid|
star.linked_by << new_kid
end
end
in view for the _connect_kid.html.erb helper method:
<%= form_for current_parent.add_kid_connection(@new_kid) do |f|%>
<div class="field">
<%= f.label "Connect it!" %><br />
<%= f.text_field :new_id %>
<div class="actions"> <%= f.submit %>
</div>
<% end %>
in *kids_controller*:
def show
@kid = Kid.find(params[:id])
@new_kid = Kid.find(params[:new_id])
In the end I get Couldn't find Kid without an ID error for the new_kid line..
Apparently it's something basic, but still trying to figure out...
Thanks!
Upvotes: 0
Views: 164
Reputation: 1806
for example you can add following method for adding some Kid to all Connections of Kids of some parent
class Parent
def add_kid_connection(new_kid)
kids.each do |kid|
kid.connected_to << new_kid
end
end
end
Upvotes: 0