vendredi 27 février 2015

Rails 3: Creating a form with nested attributes

I need to create a form that involves three hierarchies. For example, the form allows the user to create and edit the "company_apps" which belong to a particular company. Each of these "company_apps" can have one or more "app patterns". Creating a form for company_apps nested within a company seems simple enough but I'm confused on how to organize the form so that the user can create one or more app patterns for each particular company_app. Posted is a bullet points list of how I'm trying to arrange the form.



  • Company App Name, text_field

  • Company App Category, select_tag

  • Company App Tags, select_tag <- (Can have 0 or many) App Patterns (can have 0 or many)

  • App Pattern name, text_field

  • App Pattern classification, select_tag


comany.rb



class Company < ActiveRecord::Base
has_many :company_apps, :foreign_key => 'ca_company_id'
accepts_nested_attributes_for :company_apps
end


company_app.rb



class CompanyApp < ActiveRecord::Base
self.table_name = 'company_apps'
has_many :app_patterns, :foreign_key => 'ap_id'
belongs_to :company, :foreign_key => 'ca_company_id'
end


app_pattern.rb



class AppPattern < ActiveRecord::Base
belongs_to :company_apps, :foreign_key => 'ap_ca_id'
end


_form.html.haml



= form_for(@company) do |form|
%table
%tr
%td
%h2 Company Apps

%td
- companyApps = @company.company_apps
- tags = Tag.order_by(:tag_title).all.collect{ |t| [t.tag_title, t.tag_id] }
- selected = Hash.new

- companyApps.each_with_index do |ca, idx_ca|
- options = options_for_select(tags, ca.tag_ids)
- html_options = { :multiple => true, :size => 8, :class => 'chosen', 'data-placeholder' => 'Select Tags'}
%tr
%td
=label_tag ca.ca_name
%td
= select_tag "tag_ids[#{ca.ca_id}][]", options, html_options

%tr
%td
- categories = [['category1', 1], ['category2', 2], ['category3', 3], ['category4', 4], ['category5', 5], ['category6', 6]]
- options = options_for_select(categories)
= select_tag 'company[category_ids][]', options, :prompt => "Select Category"
%tr
%td
%h5 App Patterns
%tr
%td
%h2= form.label ca.app_patterns, "App Pattern Name:"
=form.text_field ca.app_patterns


%tr
%td
%h2 Save Button
%td.submit= form.submit("Save", :class => 'submit')
%tr
%td
%h2 Cancel Button
%td.submit= button_link("Cancel", companies_path, 'submit')


Do I need to add another nested attributes statement to one of my models? How do I arrange the form correctly? Currently, I am getting the following error:



undefined method `#<AppPattern:0x007f8ee71525e8>' for #<Company:0x007f8ee713b0a0>

Aucun commentaire:

Enregistrer un commentaire