Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fields from an association (has_many) model with formtastic in rails

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!

like image 960
pdu Avatar asked Feb 03 '10 21:02

pdu


2 Answers

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 %>
like image 88
pdu Avatar answered Oct 25 '22 20:10

pdu


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}" } %>
like image 4
Simon Woodside Avatar answered Oct 25 '22 19:10

Simon Woodside