Related
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
I'm getting a mass assignment error when submitting a nested form for a has_one polymorphic model. The form is trying to create Employee and Picture instances based on the polymorphic association Rails guide.
I would appreciate literally ANY functioning example of a nested creation form for a has_one polymorphic model! I know there are tons of questions on mass assignment errors but I've never seen a working example with polymorphic associations.
Models
class Picture < ActiveRecord::Base
belongs_to :illustrated, :polymorphic => true
attr_accessible :filename, :illustrated
end
class Employee < ActiveRecord::Base
has_one :picture, :as => :illustrated
accepts_nested_attributes_for :picture
attr_accessible :name, :illustrated_attribute
end
Migrations
create_table :pictures do |t|
t.string :filename
t.references :illustrated, polymorphic: true
end
create_table :employees do |t|
t.string :name
end
controllers/employees_controller.rb
...
def new
#employee = Employee.new
#employee.picture = Picture.new
end
def create
#employee = Employee.new(params[:employee])
#employee.save
end
...
Error
Can't mass-assign protected attributes: illustrated
app/controllers/employees_controller.rb:44:in `create'
{"utf8"=>"✓", "authenticity_token"=>"blah"
"employee"=>{"illustrated"=>{"filename"=>"johndoe.jpg"},
"name"=>"John Doe"},
"commit"=>"Create Employee"}
In the models, I've tried every permutation of :illustrated, :picture, :illustrated_attribute, :illustrated_attributes, :picture_attribute, :picture_attributes, etc. Any tips or examples?
EDIT:
_form.html.erb
<%= form_for(#employee) do |f| %>
<%= f.fields_for :illustrated do |form| %>
<%= form.text_field :filename %>
<% end %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
You need to specify the nested_attributes appropriately. accepts_nested_attributes_for takes the name of the association as parameter and then you need to add the same assoc_attributes to your attr_accessible. So change your Employee model to
class Employee < ActiveRecord::Base
has_one :picture, :as => :illustrated
accepts_nested_attributes_for :picture
attr_accessible :name, :picture_attribute
end
And change the field_for line in the view code to
<%= f.fields_for :picture do |form| %>
I am working on a Rails application and currently I have 2 models - Subjects and Lessons.
A Subject has 3 different types of lessons - Lecture, Tutorial and Laboratory. I modelled such that there are 3 has_one to the Lesson model.
Right now, I am trying to create a nested form for subjects and lessons but the lecture, tutorial and laboratory being saved was always the first form that was rendered.
i.e. I have 3 nested forms separately for Lecture, Tutorial and Laboratory but the Lecture, Tutorial and Laboratory that was saved was always the one that was first built. In my codes the lecture was first built so the attributes for tutorial and laboratory would follow the one that I have filled in for my lecture.
I am not sure where I have went wrong or even if having multiple has_one relationship works in this case so any advice would be appreciated.
The related codes are as follows:
The subject model
class Subject < ActiveRecord::Base
has_one :lecture, :class_name => "Lesson"
has_one :laboratory,:class_name => "Lesson"
has_one :tutorial, :class_name => "Lesson"
accepts_nested_attributes_for :lecture
accepts_nested_attributes_for :laboratory
accepts_nested_attributes_for :tutorial
end
The lesson model
class Lesson < ActiveRecord::Base
belongs_to :subject
end
The Subject and lesson nested form
<%= form_for(#subject_list) do |f| %>
<div class="field">
<%= f.label :subject_code %><br />
<%= f.text_field :subject_code %>
</div>
<div>
<%= f.fields_for :lecture do |lecture| %>
<%= render "lecture_fields", :f => lecture %>
<% end %>
</div>
<div>
<%= f.fields_for :tutorial do |tutorial| %>
<%= render "tutorial_fields", :f => tutorial %>
<% end %>
</div>
<div>
<%= f.fields_for :laboratory do |laboratory| %>
<%= render "laboratory_fields", :f => laboratory %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
The new action in the subject controller
def new
#subject = Subject.new
lecture = #subject.build_lecture
laboratory = #subject.build_laboratory
tutorial = #subject.build_tutorial
respond_to do |format|
format.html # new.html.erb
format.json { render json: #subject }
end
end
I would appreciate if someone could help me out in identifying where I have went wrong. If in the case that I should not be creating such multiple relationships, I would like to have some advice on how could I actually render out 3 forms with a default field indicating the lesson type.
I'm not really sure if that works, but my advise is to use AR inheritance
class Lesson < ActiveRecord::Base
end
class LectureLesson < Lesson
belongs_to :subject
end
class LaboratyLesson < Lesson
belongs_to :subject
end
class TutorialLesson < Lesson
belongs_to :subject
end
class Subject
has_one :lecture_lesson
has_one :laboratory_lesson
has_one :tutorial_lesson
accepts_nested_attributes_for :lecture_lesson
accepts_nested_attributes_for :laboratory_lesson
accepts_nested_attributes_for :tutorial_lesson
end
Migration
class LessonsAndSubjects < ActiveRecord::Migration
def up
remove_column :subjects, :lesson_id
add_column :subjects, :lecture_lesson_id, :integer
add_column :subjects, :laboratory_lesson_id, :integer
add_column :subjects, :tutorial_lesson_id, :integer
add_column :lessons, :type, :string
add_index :subjects, :lecture_lesson_id
add_index :subjects, :laboratory_lesson_id
add_index :subjects, :tutorial_lesson_id
end
def down
remove_column :subjects, :lecture_lesson_id
remove_column :subjects, :laboratory_lesson_id
remove_column :subjects, :tutorial_lesson_id
remove_column :lessons, :type
add_column :subjects, :lesson_id, :integer
end
end
it makes more sense and it may be fix you issue with nested attributes
Actually from the answer from rorra one point is missing, you need to add a polymorphic association for each "children" to not incurr in query problems
class Lesson < ActiveRecord::Base
belongs_to :subject
end
class LectureLesson < Lesson
belongs_to :polymorphic_lecture_lesson, polymorphic: true
end
class Subject
has_one :lesson
has_one :lecture_lesson, as: :polymorphic_lecture_lesson
accepts_nested_attributes_for :lesson
accepts_nested_attributes_for :lecture_lesson
end
in migration you have then to add
add_column :lessons, :polymorphic_lecture_lesson_id, :integer, index: true
add_column :lessons, :polymorphic_lecture_lesson_type, :integer, index: true
Interestingly, I interpreted this question much differently than the other answers seem to have.
If you are looking to have 2 has_one to a single model/table, then one can do the following:
Given a Person has one best pet and one worst pet, which are represented by the same Pet table/model that has an attribute to differentiate between the two...
class Person < ApplicationRecord
has_one :best_pet, -> { where(pet_type: "best") }, class_name: "Pet"
has_one :worst_pet, -> { where(pet_type: "worst") }, class_name: "Pet"
...
end
class Pet < ApplicationRecord
belongs_to :person
validates_presence_of :pet_type
validates_uniqueness_of :pet_type, scope: :person_id
...
end
Now, whether or not this is good database design is up for debate.
I have two models, Artist and User that are connected through a third model, ArtistMembership.
From the edit/new Artist form, I want to be able to edit the role of any User in an existing ArtistMembership relationship for that Artist, delete ArtistMemberships, and add new AtistMembership relationships, which would include a User and :role.
Here's my Artist model:
class Artist < ActiveRecord::Base
has_many :artist_memberships, foreign_key: "artist_id", dependent: :destroy
attr_accessible :bio, :created_at, :email, :location, :name, :updated_at, :website, :pic
accepts_nested_attributes_for :artist_memberships, :allow_destroy => :true
...
end
Here's my User model:
class User < ActiveRecord::Base
...
has_many :artist_memberships, foreign_key: "user_id"
...
end
Here's my ArtistMembership model:
class ArtistMembership < ActiveRecord::Base
belongs_to :artist, class_name: "Artist"
belongs_to :user, class_name: "User"
attr_accessible :artist_id, :created_at, :role, :user_id
end
If I have a _form.hml.erb too, for editing Artists that starts:
<%= form_for #artist do |artist_form| %>
<div class="field">
<%= artist_form.label :name %>
<%= artist_form.text_field :name %>
</div>
..
<div class="actions">
<%= artist_form.submit %>
</div>
<% end %>
how can I create the related ArtistMembership forms for the aforementioned functionality?
May be this is helpful for you, see this field_for
you can use accepts_nested_attributes_for(*attr_names)
Maybe you are looking for this method.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
Refer to the "One-to-many" section.
But if I were you, I would rather use the "Nested Resource" technic.
http://guides.rubyonrails.org/routing.html#nested-resources
Editing my question for conciseness and to update what I've done:
How do I model having multiple Addresses for a Company and assign a single Address to a Contact, and be able to assign them when creating or editing a Contact?
I want to use nested attributes to be able to add an address at the time of creating a new contact. That address exists as its own model because I may want the option to drop-down from existing addresses rather than entering from scratch.
I can't seem to get it to work. I get a undefined method `build' for nil:NilClass error
Here is my model for Contacts:
class Contact < ActiveRecord::Base
attr_accessible :first_name, :last_name, :title, :phone, :fax, :email, :company,
:date_entered, :campaign_id, :company_name, :address_id, :address_attributes
belongs_to :company
belongs_to :address
accepts_nested_attributes_for :address
end
Here is my model for Address:
class Address < ActiveRecord::Base
attr_accessible :street1, :street2, :city, :state, :zip
has_many :contacts
end
I would like, when creating an new contact, access all the Addresses that belong to the other Contacts that belong to the Company. So here is how I represent Company:
class Company < ActiveRecord::Base
attr_accessible :name, :phone, :addresses
has_many :contacts
has_many :addresses, :through => :contacts
end
Here is how I am trying to create a field in the View for _form for Contact so that, when someone creates a new Contact, they pass the address to the Address model and associate that address to the Contact:
<% f.fields_for :address, #contact.address do |builder| %>
<p>
<%= builder.label :street1, "Street 1" %> </br>
<%= builder.text_field :street1 %>
<p>
<% end %>
When I try to Edit, the field for Street 1 is blank. And I don't know how to display the value from show.html.erb.
At the bottom is my error console -- can't seem to create values in the address table:
My Contacts controller is as follows:
def new
#contact = Contact.new
#contact.address.build # Iundefined method `build' for nil:NilClass
#contact.date_entered = Date.today
#campaigns = Campaign.find(:all, :order => "name")
if params[:campaign_id].blank?
else
#campaign = Campaign.find(params[:campaign_id])
#contact.campaign_id = #campaign.id
end
if params[:company_id].blank?
else
#company = Company.find(params[:company_id])
#contact.company_name = #company.name
end
end
def create
#contact = Contact.new(params[:contact])
if #contact.save
flash[:notice] = "Successfully created contact."
redirect_to #contact
else
render :action => 'new'
end
end
def edit
#contact = Contact.find(params[:id])
#campaigns = Campaign.find(:all, :order => "name")
end
Here is a snippet of my error console:
I am POSTING the attribute, but it is not CREATING in the Address table....
Processing ContactsController#create
(for 127.0.0.1 at 2010-05-12 21:16:17)
[POST] Parameters:
{"commit"=>"Submit",
"authenticity_token"=>"d8/gx0zy0Vgg6ghfcbAYL0YtGjYIUC2b1aG+dDKjuSs=",
"contact"=>{"company_name"=>"Allyforce",
"title"=>"", "campaign_id"=>"2",
"address_attributes"=>{"street1"=>"abc"},
"fax"=>"", "phone"=>"",
"last_name"=>"",
"date_entered"=>"2010-05-12",
"email"=>"", "first_name"=>"abc"}}
Company Load (0.0ms)[0m [0mSELECT
* FROM "companies" WHERE ("companies"."name" = 'Allyforce')
LIMIT 1[0m
Address Create (16.0ms)[0m
[0;1mINSERT INTO "addresses" ("city",
"zip", "created_at", "street1",
"updated_at", "street2", "state")
VALUES(NULL, NULL, '2010-05-13
04:16:18', NULL, '2010-05-13
04:16:18', NULL, NULL)[0m
Contact Create (0.0ms)[0m
[0mINSERT INTO "contacts" ("company",
"created_at", "title", "updated_at",
"campaign_id", "address_id",
"last_name", "phone", "fax",
"company_id", "date_entered",
"first_name", "email") VALUES(NULL,
'2010-05-13 04:16:18', '', '2010-05-13
04:16:18', 2, 2, '', '', '', 5,
'2010-05-12', 'abc', '')[0m
Just a banal question, if you using this in your contact form shouldn't be address in singular?
<% f.fields_for :address, #contact.address do |builder| %>
<p>
<%= builder.label :street1, "Street 1" %> </br>
<%= builder.text_field :street1 %>
<p>
<% end %>
In your action you have also to do
#ycontact.build_address
If you look at the source code your input field should look like.
< input type="text" size="30"
name="contact[address_attributes][street1]"
id="contact_address_attributes_street1">
I think you also have problems with your associations, if you store address_id in contact then
class Contact < ActiveRecord::Base
belongs_to :address
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
attr_accessible :street1
has_many :contacts
end
And i think this is your case because you want to assign an address to multiple contacts.
You can also do in inverse, if you store your contact_id in your address model:
class Contact < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
attr_accessible :street1
belongs_to :contact
end
In this case you cant have users with the same address.
Update
In your user show.html.eb you can use
<%= #contact.address.street1 %>
In your company's show.html.erb you can display the addresses like:
<% #company.addresses.each do |address| %>
<%= address.street1 %>
...
<% end %>
On your user edit page the form fields should be the same as at new.html.erb just the form tag should look like:
<% form_for #contact do |form| %>
<%=render :partial=>'fields' %>
<% end %>
The fields partial contains all your fieds togheter with the:
<% f.fields_for :address, #contact.address do |builder| %>
<p>
<%= builder.label :street1, "Street 1" %> </br>
<%= builder.text_field :street1 %>
<p>
<% end %>
This should work.
Update 2
You can access all the addresses which belong to a company with:
#company.addresses
If you have
class Company<Activerecord::Base
has_many :contacts
has_many :addresses, :through=>:contacts
end
About the drafts, or default addresses. You can have different options depending on your needs. I you want the option that a contact could select one of the existing addresses from the database. You can do a select box in your contact form like:
<%= form.select :address_id, options_from_collection_for_select(#company.addresses, 'id', 'street1')%>
Also you can use some fancy javascript to add or remove the address form, in that case if the user chooses one of the existing addresses. In this case you have to remove the address_attributes from the form. I suggest to create a link with javascript code that adds the address_attributes and removes (toggle style).
If each Address belongs to only one Contact, (like a home address), you could do:
class Company < ActiveRecord::Base
has_many :contacts
end
class Contact < ActiveRecord::Base
belongs_to :company
has_one :address
end
class Address < ActiveRecord::Base
belongs_to :contact
end
Of course, you could just move the address columns into the Contact table and get rid of the Address model altogether.
If each Address has multiple contacts (ie, the addresses are company facilities where the contacts work):
class Company < ActiveRecord::Base
has_many :contacts
end
class Contact < ActiveRecord::Base
belongs_to :company
belongs_to :address
end
class Address < ActiveRecord::Base
has_many :contacts
end
You can add a has_many :through association to get company.addresses:
class Company < ActiveRecord::Base
has_many :contacts
has_many :addresses, :through => :contacts
end
In both situations the address components (street, city, state, etc) are columns in the addresses table.
The last part of your question really depends on the data distribution -- if you have only a few addresses, you could simply stick them in a select element with the main address as the default. With more addresses you might need an AJAXified form with autocomplete that search the addresses table.
To get the new contacts/addresses into your tables, you might want to look at nested forms. Railscast 196 is a good introduction.
EDIT -- more about nested attributes
accepts_nested_attributes_for should work with either a has_many or has_one assocation, and should work with multiple levels of nesting. It seems that you want to have a Contact belong to a Company, and an Address to belong to a Contact, in which case:
class Company < ActiveRecord::Base
has_many :contacts
accepts_nested_attributes_for :contact
end
class Contact < ActiveRecord::Base
belongs_to :company
has_one :address # or has_many, if you prefer
end
class Address < ActiveRecord::Base
belongs_to :contact
end
Then in the view use form_for and fields_for as described in the Railscast to get the nested form elements. This can be a bit tricky to get right if your form is unusual. There are excellent examples from ryanb here that cover several typical situations.
Since you want an address to belong both to a company and to a contact, you have two choices. If you aren't going to ever need multiple addresses (which I might recommend against assuming), then you can put a "belongs_to :address" in both Company and Contact. Address would then have both a "has_many :companies" and "has_many :contacts".
The better option that makes more sense is to use polymorphic associations, where the address table would have :addressable_type and :addressable_id columns to link back to either model.
class Company < ActiveRecord::Base
attr_accessible :name, :phone, :addresses
has_many :contacts
accepts_nested_attributes_for :contacts
has_many :addresses, :as => :addressable
accepts_nested_attributes_for :addresses
end
class Contact < ActiveRecord::Base
attr_accessible :first_name, :last_name, :title, :phone, :fax, :email, :company,
:date_entered, :campaign_id, :company_name
belongs_to :company
has_many :addresses, :as => :addressable
accepts_nested_attributes_for :addresses
end
class Address < ActiveRecord::Base
attr_accessible :street1
belongs_to :addressable, :polymorphic => true
end
Now your trouble comes with wanting to have a single association "company.addresses" to get both it's address and those of its contacts. I might recommend staying away from this and using a different approach.
You're going to want to map those addresses in the view to the correct record, so it might be best to separate them:
<% form_for #company do |company_form| %>
<% company_form.fields_for :addresses do |address_form| %>
<%= address_form.text_field :street1 %>
<% end %>
<% company_form.fields_for :contacts do |contact_form| %>
<% contact_form.fields_for :addresses do |contact_address_form| %>
<%= contact_address_form.text_field :street1 %>
<% end %>
<% end %>
<% end %>
Your address table has the polymorphic columns like this:
class CreateAddresses < ActiveRecord::Migration
def self.up
create_table :addresses do |t|
t.string :street1
t.string :addressable_type
t.integer :addressable_id
t.timestamps
end
end
def self.down
drop_table :addresses
end
end
I'm not sure how you could keep all the linking straight if you don't nest the records individually like this.
If you do need to get all the addresses for a company for display purposes, you could use the standard ruby enumerable manipulations like collect to gather them together.
Good luck!
I'd recommend to let the Contact have many addresses. It happens anyways in the wild. If decided for only one, that would be has_one :address
Oh and you must downcase them: has_many :Contacts must be has_many :contacts
In the Address model you reference with (database needs a addressable_id and addressable_type field)
belongs_to :addressable, :polymorphic => true