rails nested one to many form with fields_for built from a query
I'm working on a Rails project where I need to provide the user with a
subform as follows: For each of N resources, a text string with the
resource name and a text box where the user can enter a desired amount.
Upon submission of the form, my code saves -only- those M <= N
resource-amount pairs for which the user has entered something.
I want the user to be able to go back to this form at any time. The form
would retrieve the M resource-amount pairs and display all N resources as
before (obviously the N-M resources not specified would have an empty text
box).
The models look like this:
class RequestReview < ActiveRecord::Base attr_accessible :request_id,
:panel_member_id, :request_status_type_id, :overall_rating_type_id,
:review, :reviewer_resource_attributes
validates(:review, presence: true) validates(:overall_rating_type_id,
presence: true)
before_save { self.date_reviewed = Time.now}
def reviewer_resource_attributes=(reviewer_resource_attributes)
reviewer_resource_attributes.each do |attributes|
request_reviewer_resources.build(attributes)
end
end
self.primary_key = :request_review_id
belongs_to :panel_member, :class_name => 'PanelMember', :foreign_key =>
:panel_member_id
belongs_to :request, :class_name => 'Request', :foreign_key => :request_id
belongs_to :overall_rating_type, :class_name => 'OverallRatingType',
:foreign_key => :overall_rating_type_id
has_many :request_reviewer_resources, :class_name =>
'RequestReviewerResource', :foreign_key => :request_review_id,
:dependent => :destroy
end
class RequestReviewerResource < ActiveRecord::Base attr_accessible
:resource_id, :suggested_amount, :comments
self.primary_key = :request_reviewer_resource_id
belongs_to :resource, :class_name => 'Resource', :foreign_key => :resource_id
belongs_to :request_review, :class_name => 'RequestReview', :foreign_key
=> :request_review_id
end
Here's the rub: If I use the code below, the first time I use the subform
it works beautifully, however any subsequent use results in replicated
form entries:
: Resource comment: resource.resource_id %>
<% end %>
If I remove the nested "for" for second and later subform accesses, then I
don't get replicated entries, however the code obviously cannot display
the resource name (resource.resource_name)--it only works if I put a
generic label for every resource.
Any ideas as to how to overcome this?
No comments:
Post a Comment