views:

792

answers:

3

I searched and tried a lot, but I can't accomplish it as I want.. so here's my problem.

class Moving < ActiveRecord::Base
  has_many :movingresources, :dependent => :destroy
  has_many :resources, :through => :movingresources
end

class Movingresource < ActiveRecord::Base
  belongs_to :moving
  belongs_to :resource
end

class Resource < ActiveRecord::Base
  has_many :movingresources
  has_many :movings, :through => :movingresources
end

Movingresources contains additional fields, like "quantity". We're working on the views for 'bill'. Thanks to formtastic to simplify the whole relationship thing by just writing

<%= form.input :workers, :as => :check_boxes %>

and i get a real nice checkbox list. But what I haven't found out so far is: How can i use the additional fields from 'movingresource', next or under each checkbox my desired fields from that model?

I saw different approaches, mainly with manually looping through an array of objects and creating the appropriate forms, using :for in a form.inputs part, or not. But none of those solutions were clean (e.g. worked for the edit view but not for new because the required objects were not built or generated and generating them caused a mess).

I want to know your solutions for this! :-)

+1  A: 

If the fields don't exist in the new view, you can just test if it is new (new_record?) and present a different set of fields (if you wrap into a partial in can be quite a clean approach).

Toby Hede
thanks, you're right. But since i work with rails, I'm used to simplicity, therefore I'm asking for other solutions to pick my favourite. And I also think this may help some other people.
pduersteler
+1  A: 

Okay, I missed the revolution of accepts_nested_attributes_for, this explains why it's not really working.

This got me a big step further, but I think somewhere I will still have some complications with my complex relations ^_^

class Moving < ActiveRecord::Base
    has_many :movingworkers, :dependent => :destroy
    has_many :workers, :through => :movingworkers
    accepts_nested_attributes_for :movingworkers
end


<% form.inputs :for => :movingworkers do |movingworker| %>
    <%= movingworker.inputs :worker, :quantity %>
<% end %>
pduersteler
+1  A: 

Formtastic's :label_method option might help. E.g.

<%= form.input :movingworkers, :label_method => :worker %>

or

<%= form.input :movingworkers, :label_method => Proc.new { |x| "#{x.worker} #{x.quantity}" } %>
sbwoodside