Nested forms with multiple table inheritance - ruby-on-rails

How do I build a nested form for objects using multiple table inheritance in rails? I am trying to make a nested form to create an object using a model with a has_many relationship to another set of models that feature multi-table inheritance. I am using formtastic and cocoon for the nested form and the act_as_relation gem to implement the multiple table inheritance.
I have the following models:
class Product < ActiveRecord::Base
acts_as_superclass
belongs_to :store
end
class Book < ActiveRecord::Base
acts_as :product, :as => :producible
end
class Pen < ActiveRecord::Base
acts_as :product, :as => :producible acts_as :product, :as => :producible
end
class Store < ActiveRecord::Base
has_many :products
accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank
end'
For this example, the only unique attribute that book has compared to other products is an author field. In reality, I have a number of unique attributes for book which is why I chose multi-table inheritance over the more commonplace single table inheritance.
I am trying to create a nested form that allows you to create a new store with products. Here's my form:
<%= semantic_form_for #store do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<h3>Books/h3>
<div id='books'>
<%= f.semantic_fields_for :books do |book| %>
<%= render 'book_fields', :f => book %>
<% end %>
<div class='links'>
<%= link_to_add_association 'add book', f, :books %>
</div>
<% end %>
<%= f.actions :submit %>
<% end %>
And the book_fields partial:
<div class='nested-fields'>
<%= f.inputs do %>
<%= f.input :author %>
<%= link_to_remove_association "remove book", f %>
<% end %>
</div>
I get this error:
undefined method `new_record?' for nil:NilClass
Based on reading the issues on the github page for act_as_relation, I thought about making the relationship between store and books more explicit:
class Product < ActiveRecord::Base
acts_as_superclass
belongs_to :store
has_one :book
accepts_nested_attributes_for :book, :allow_destroy => true, :reject_if => :all_blank
end
class Book < ActiveRecord::Base
belongs_to :store
acts_as :product, :as => :producible
end
class Store < ActiveRecord::Base
has_many :products
has_many :books, :through => :products
accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :all_blank
accepts_nested_attributes_for :books, :allow_destroy => true, :reject_if => :all_blank
end
Now, I get a silent error. I can create new stores using the form, and cocoon allows me to add new book fields, but when I submit the store gets created but not the child book. When, I go through the `/books/new' route, I can create a new book record that spans (the products and books table) with no problem.
Is there a workaround to this problem? The rest of the code can be found here.

Maybe you could:
Build the books relation manually on your stores_controller#new action
#store.books.build
Store manually the relation on you stores_controller#create action
#store.books ... (not really confident on how to achieve it)
Keep us posted.

You might want to consider creating your own form object. This is a RailsCast pro video, but here are some of the examples in the ASCIIcast:
def new
#signup_form = SignupForm.new(current_user)
end
This signup form can include relations to your other objects, just as you would in your original controller code:
class SignupForm
# Rails 4: include ActiveModel::Model
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
validates_presence_of :username
validates_uniqueness_of :username
validates_format_of :email, with: /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/
validates_length_of :password, minimum: 6
def persisted?
false
end
def subscribed
subscribed_at
end
def subscribed=(checkbox)
subscribed_at = Time.zone.now if checkbox == "1"
end
def generate_token
begin
self.token = SecureRandom.hex
end while User.exists?(token: token)
end
end
Here is the link to the RailsCast. Getting a pro membership might be worth your time. I have been getting lucky with a membership through www.codeschool.com where you can get 'prizes' when you finish courses:
RailsCast:
http://railscasts.com/episodes/416-form-objects

Related

Rails create dynamic attributes

I'm trying to make e-commerce shop with RoR. Most of the required functionality I did without any problems, but now I really need somebody's help here.
I want to make product attributes, like a "Size", "Weight", "Color", etc.
Easiest way is to define this attributes in model migration, but now I want to make attributes dynamic. The main problem is that I can't get all params with attributes from forms when trying to create product.
products/new.html.erb
<%= form_for #product, url: admin_products_path(#product) do |f| %>
<%= f.label :name, 'Name' %>
<%= f.text_field :name, class: "form-control" %>
<%= text_field_tag "product[product_feature][]" %>
<%= text_field_tag "product[product_feature][]" %>
<%= f.submit "Submit" %>
<% end %>
So, I want to generate many fields with attribute name and value, fill them and use these params in controller to interate them and finally create product attributes.
Like
params[:product_features].each do |k, v|
ProductFeature.create(name: k, value: v, product_id: product_id)
end
All gems, that can manipulate with dynamic attributes aren't working with Rails 5+, so I need to find solution for this problem.
I even have working simple db solution for this, but it's uncomfortable to create params. Here it is.
Product.rb
class Product < ApplicationRecord
has_many :product_features
has_many :features, :through => :product_features
end
ProductFeature.rb
class ProductFeature < ApplicationRecord
belongs_to :product
belongs_to :feature
end
Feature.rb
class Feature < ApplicationRecord
end
Make a new model, a child of product called ProductAttribute with two attributes.
Class ProductAttribute < ApplicationRecord
belongs_to :product
validates :name, presence: true
validates :value, presence: true
end
Then use cocoon, or just accepts_nested_attributes
class Product < ApplicationRecord
has_many :product_attributes, as: :attributes
accepts_nested_attributes_for :attributes, allow_destroy: true
end
class ProductsController < ApplicationController
.
.
.
private
.
.
def product_params
params.require(:product).permit(. . . attributes_attributes: [:id, :name, :value])
end
end
Cocoon is definitely what you're looking for.
Heres a quick example i found
class Product
belongs_to :collection
end
class Collection
has_many :products
end
and then in your view something like this
<%= collection_select(:product, :collection_id, Collection.all, :id, :name) %>

Form for has_many :trough association with creating object

Problem
With my rails app I'm trying to accomplish something like image below.
Invoice should has many Items. For example Invoice_1 would have in invoice_items container:
[{item: Egg, quantity: 3, unit_price: 4}, {item: Stick, quantity: 4, unit_price: 2}].
How to made a form to add n Items to Invoice?
Or how to edit this form/controller to create fixed number of InvoiceItems for a start. Later I'll figure how to create Items and create associations dynamically in html.
Source
Models
class Item < ActiveRecord::Base
has_many :invoice_items
has_many :invoices, through: :invoice_items
end
class Invoice < ActiveRecord::Base
has_many :invoice_items, inverse_of: :invoice
has_many :items, through: :invoice_items
accepts_nested_attributes_for :invoice_items
validates :items, :length => { :minimum => 1 }
end
class InvoiceItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :item
validates_presence_of :invoice
validates_presence_of :item
accepts_nested_attributes_for :item
end
Invoice controller
# GET /invoices/new
def new
#invoice = Invoice.new
#invoice.invoice_items.build
end
private:
def invoice_params
#params.fetch(:invoice, {})
params.require(:invoice).permit(
:date,
:seller_id,
:client_id,
invoice_items_attributes: [ item_attributes:
[:name, :quantity, :unit, :unit_price_cents, :unit_price_currency, :price_cents, :price_currency ]
],
invoice_name_attributes: [:number, :month, :year],
)
end
Invoice form
<%= form_for(#invoice) do |invoice_form| %>
<%= invoice_form.fields_for :invoice_items do |invoice_item_form| %>
<%= invoice_item_form.fields_for :item do |item_form| %>
<%= item_form.text_field :name %>
<% end %>
<% end %>
<div class="actions">
<%= invoice_form.submit %>
</div>
<% end %>
Based on what I'm reading, you probably just want to focus on making InvoiceItem records built from an invoice. You can build a fixed number (n) of invoice items by using code such as n.times { invoice.invoice_items.build } in the new method in your controller.
When you want to create dynamic fields there is a gem called Cocoon which allows you to dynamically add associated records to a form.
My advice is just to use fields_for :invoice_items as you have done already in your form and omit the fields_for :items. Instead in the invoice_items form add a select_tag that includes all of the Items you want to add to an invoice.

How to setup a deeply nested form in Rails 3.2

I'm trying to build a rather complex nested form in rails and am stuck.
Basically, I have three models - Applicant, DataPoint, ApplicantDataPointValue .
The user can create a new DataPoint, give it a name ("gender" etc.) select it's type ("string","integer" etc.). The type determines what column the data will eventually be saved in in the ApplicantDataPointValue table.
I then want the user, when they're creating a new Applicant, to be able to add a value for each DataPoint into the ApplicantDataPointValue table
My models look like the following:
Applicant:
class Applicant < ActiveRecord::Base
has_many :applicant_data_point_values, dependent: :destroy
has_many :data_points, :through => :applicant_data_point_values
accepts_nested_attributes_for :data_points
accepts_nested_attributes_for :applicant_data_point_values
attr_accessible :data_points_attributes, :applicant_data_point_values_attributes
end
DataPoint:
class DataPoint < ActiveRecord::Base
has_many :applicant_data_point_values
has_many :applicants, :through => :applicant_data_point_values
accepts_nested_attributes_for :applicant_data_point_values
end
ApplicantDataPointValue:
class ApplicantDataPointValue < ActiveRecord::Base
belongs_to :data_point
belongs_to :applicant
end
But I'm at a loss to what to do in the 'new' and 'create' sections of my controller or how to construct the form.
Any insight would be greatly appreciated.
From what I understand, the form for the User will also have multiple ApplicantDataPointValue fields. (but that form won't allow creating of new DataPoint fields, right?)
In the controller new action, you'll want to set up your model with associated data point values:
def new
#user = User.new
DataPoint.all.each do |data_point|
applicant_data_point_value = #user.applicant_data_point_values.build
applicant_data_point_value.data_point = data_point
end
end
And then, display a text box for each data point value.
<%= form_for #user do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<% #user.applicant_data_point_values.each do |data_point_value| %>
<%= f.fields_for :applicant_data_point_values, data_point_value do |fields| %>
<%= fields.label :value, data_point_value.data_point.type %>
<%= fields.text_field :value %>
<% end %>
<% end %>
Reference: http://railscasts.com/episodes/196-nested-model-form-part-1

Rails 3 Data Modeling Help - Has Many, Belongs to, Nested Atrributes

I am working on a project involving three models (recipient, award, announcer) and need to have a nested attributes when issuing an award by an announcer to multiple recipients. For an example, award form need to have the ability to do 3 things:
Can add multiple-recipients (i.e. "add recipient", "remove recipient") - nested attributes
After creating a new award, the award will be posted into recipient's profile.
Enables future polling of #recipient.awards and #announcer.awards
Really struggle in terms of how to smartly solve this problem. The following data structure kind of made sense, however can not do "accepts_nested_attributes_for :recipients" in the award form. Can you help? Many thanks in advance.
class Recipient < ActiveRecord::Base
has_many :awards
has_many :announcers, :through => :awards
end
class Announcer < ActiveRecord::Base
has_many :awards
has_many :recipients, :through => :awards
end
class Award < ActiveRecord::Base
belongs_to :announcer
belongs_to :recipient
end
You're just about there. The main issue is that you're trying to create recipient objects in the form rather than just creating a relationship between the award and another object (user). You could do something like this:
class User < ActiveRecord::Base
has_many :recipients
has_many :awards, :through => :recipients
end
# this is your relationship between an award and a user
class Recipient < ActiveRecord::Base
belongs_to :user
belongs_to :award
end
class Award < ActiveRecord::Base
has_many :recipients
has_many :users, :through => :recipients
belongs_to :announcer
accepts_nested_attributes_for :recipients, :allow_destroy => true
end
class Announcer < ActiveRecord::Base
has_many :awards
has_many :recipients, :through => :awards
end
Then you would just do a nested form that would build the recipients_attributes array:
<%= form_for #award do |f| %>
<%= f.text_field :name %>
<div id="recipients">
<% #award.recipients.each do |recipient| %>
<%= render :partial => '/recipients/new', :locals => {:recipient => recipient, :f => f} %>
<% end %>
</div>
<%= link_to_function 'add recipient', "jQuery('#recipients').append(#{render(:partial => '/recipients/new').to_json})" %>
<% end %>
And, to keep it DRY just push the nested part into a partial:
# app/views/recipients/_new.html.erb
<% recipient ||= Recipient.new %>
<%= f.fields_for 'recipients_attributes[]', recipient do |rf| %>
<%= rf.select :user_id, User.all %>
<%= fr.check_box '_delete' %>
<%= fr.label '_delete', 'remove' %>
<% end %>
Obviously the User.all call isn't ideal so maybe make that an autocomplete.

Assigning a nested attribute with Formtastic

I've been trying to figure this one out for a while but still no luck. I have a company_relationships table that joins Companies and People, storing an extra field to describe the nature of the relationship called 'corp_credit_id'. I can get the forms working fine to add company_relationships for a Person, but I can't seem to figure out how to set that modifier field when doing so. Any ideas?
More about my project: People have many companies through company_relationships. With that extra field in there I am using it to group all of the specific relationships together. So I can group a person's Doctors, Contractors, etc.
My models:
Company.rb (abridged)
class Company < ActiveRecord::Base
include ApplicationHelper
has_many :company_relationships
has_many :people, :through => :company_relationships
Person.rb (abridged)
class Person < ActiveRecord::Base
include ApplicationHelper
has_many :company_relationships
has_many :companies, :through => :company_relationships
accepts_nested_attributes_for :company_relationships
company_relationship.rb
class CompanyRelationship < ActiveRecord::Base
attr_accessible :company_id, :person_id, :corp_credits_id
belongs_to :company
belongs_to :person
belongs_to :corp_credits
end
My form partial, using formtastic.
<% semantic_form_for #person do |f| %>
<%= f.error_messages %>
<% f.inputs do %>
...
<%= f.input :companies, :as => :check_boxes, :label => "Favorite Coffee Shops", :label_method => :name, :collection => Company.find(:all, :conditions => {:coffee_shop => 't'}, :order => "name ASC"), :required => false %>
So what I would like to do is something like :corp_credit_id => '1' in that input to assign that attribute for Coffee Shop. But formtastic doesn't appear to allow this assignment to happen.
Any ideas on how to do this?
Are you looking for something like
<% semantic_form_for #person do |form| %>
<% form.semantic_fields_for :company_relationships do |cr_f| %>
<%= cr_f.input :corp_credit_id %>
<% end %>
It is in the documentation

Resources