Self Referential HABTM Checkbox Example or Tutorial Needed

My checkboxes currently show up either checked or not checked based on
manually entered data using this bit so far…

<% Project.find(:all).each do |project| %>
<input type=“checkbox” id="<%= project.id %>" name=“project_ids[]”
value="<%= project.id %>"<% if @project.cross_reference.include? project
%> checked=“checked”<% end %>> <%= project.name %>

I have projects that relate to other projects in a cross_reference table
with rows for project_id and cross_reference_id.

My manually enter values can be retrieved but I can’t figure out how to
write the values to the cross_reference table from a web form.

Any reference or guidance appeciated.

Thanks,
DAN

Just a suggestion: use has_many :through instead. habtm is kinda
deprecated, at least partly.

I dunno if this helps you, but in HowTo:
http://wiki.rubyonrails.com/rails/pages/Howtos
you will find a document about many to many relations.

Besides, in
http://www.fallenrogue.com/article/view/143-I-am-what-I-am-or-self-referential-joins-in-Rails
you will find an example on self-referential joins…

Thanks for the direction.

I’ve added a cross_reference model now and in my
models/cross_reference.rb is

has_many :projects
belongs_to :project

and my models/project.rb contains

has_many :cross_references
has_many :projects, :through => :cross_references

I’m able to show manually entered data, such as discriminaing which
checkboxes for related projects should be checked - same as before, but
now using the code in my project form partial

<% Project.find(:all).each do |project| %>
<input type=“checkbox” id="<%= project.id %>" name=“project_ids[]”
value="<%= project.id %>"<% if @project.projects.include? project %>
checked=“checked”<% end %>> <%= project.name %>

<% end %>

I’m still stuck on trying to save (via my project edit or update
methods) to my cross_references table though.

I believe I need some statements in my project_controller.rb new,
create, and update methods such as:

def project_new
@project = Project.new
@cross_references = CrossReference.find(:all)
end

def project_create
@project = Project.new(params[:project])
@project.cross_references =
CrossReference.find(@params[:cross_reference_ids]) if
@params[:cross_reference_ids]
end

def project_edit
@project = Project.find(params[:id])
@cross_references = CrossReference.find(:all)
end

def project_update
@project = Project.find(params[:id])
@project.cross_references =
CrossReference.find(@params[:cross_reference_ids]) if
@params[:cross_reference_ids]
end

I hope I’m poviding enough information. It would be great to understand
how the create these kind of relationships.

DAN

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs