Rails - nested forms to link has_one's where the child object has already been created - ruby-on-rails

I have two models which are linked in a has_one / belongs_to association; Computer and Ipv6Address respectively.
I have pre-populated the Ipv6 table with all the entries that I want it to have, and I now need to have a drop-down list on the Computer new/edit forms to select an item from Ipv6 to associate it with.
Everything I've seen so far on this only seems to work when you are creating both objects at the same time on the new form and then subsequently editing them.
I've tried to set up my MVC's as per the examples I've found online, but I keep getting errors, as underneath these code excerpts:
Computer model:
class Computer < ActiveRecord::Base
accepts_nested_attributes_for :ipv6_address
has_one :ipv6_address
...
Ipv6Address model:
class Ipv6Address < ActiveRecord::Base
attr_accessible :computer_id, :ip_address
belongs_to :computer
...
Computer controller:
class ComputersController < ApplicationController
def new
#computer = Computer.new
#ipv6s = Ipv6Address.where('computer_id IS NULL').limit(5)
end
def edit
#computer = Computer.find(params[:id])
#ipv6s = Ipv6Address.where('computer_id = #{#computer.id} OR computer_id IS NULL').order('computer_id DESC').limit(5)
end
Computer new form:
<%= simple_form_for( #computer ) do |f| %>
<%= f.fields_for :ipv6_addresses do |v6| %>
<%= v6.input :ipv6_address, :collection => #ipv6s %>
<% end %>
<% f.button :submit %>
<% end %>
Error when browsing to computer new form:
NoMethodError in ComputersController#new
private method `key?' called for nil:NilClass
No line of code reference is given for this error, but it only appears when I have the nested form included in the computer new form.
Any ideas as to what is causing it or how I can better go about what I'm doing?
EDIT:
As it turns out, I needed to have accepts_nested_attributes_for :ipv6_address after the line has_one :ipv6_address in the Computer model.
That fixed the issue with the form loading.
As per Yarden's answer, I then also singularized all instances of "ipv6_address" so as to reflect the has_one relationship.
Once doing that in the new form, however, the ipv6 field completely disappeared. I'll open a new question with this one if I can't get it sorted out shortly.

Try adding ':', I think that may be the problem :
<%= f.fields_for :ipv6_addresses do |v6| %>
Also you forgot to add a '.' here:
#ipv6s = Ipv6Address.where('computer_id IS NULL').limit(5)
Edit after change:
The problem is that its only a has_one relationship so it doesnt know the plural of :ipv6_address as you stated in your model... you need to change it to :ipv6_address instead of :ipv6_addresses...
Also in your form change the :ipv6_address to the actual field which is :ip_address.
So overall your form should look like this:
<%= simple_form_for( #computer ) do |f| %>
<%= f.fields_for :ipv6_address do |v6| %>
<%= v6.input :ip_address, :collection => #ipv6s %>
<% end %>
<% f.button :submit %>
<% end %>

Related

Accessing different model elements in Rails

I am inexperienced in Rails (version 4.2.5) and struggle with how views access database elements. I have worked through a number of different tutorials but still don't really understand why it doesn't work the way I think it does!
I have models that have been set up with references which I believe that establishes foreign keys in the database. I want to edit entries in the database that belong in a different model.
So, a Wines is a model that references Winemakers.
class Wine < ActiveRecord::Base
belongs_to :winemaker
end
In my _edit_form.html.erb file I have the following code which works but does not give me what I want:
<%= simple_form_for(#wine) do |f| %>
<div class="field">
<%= f.label :winemaker_id %>
<%= f.text_field :winemaker_id %>
</div>
This produces a simple box and in the box the integer that is winemaker_id is displayed but what I want is the actual name of the winemaker. I have tried :winemaker_id.name, #winemaker.name and many variations on those theme but I clearly do not understand how this works. I have tried reading various documentation but I am none the wiser.
Can someone please explain in simple terms how accessing different models works?
If your Winemaker model has been defined as follows:
class Winemaker < ActiveRecord::Base
has_many :wines
end
That means you can write the followings:
#winemaker.wines - returns all the wines belongs to a winemaker
#wine.winemaker - returns the winemaker to whom the wine belongs
If you want to show and edit the Winemaker name from Wine form, then you can do it using accepts_nested_attributes_for
Just modify your Wine model as follows:
class Wine < ActiveRecord::Base
belongs_to :winemaker
accepts_nested_attributes_for :winemaker
end
Now you can make a small change to your form as follows:
<%= form_for #wine do |f| %>
<%= f.fields_for :winemaker do |w|%>
<%= w.text_field :name%>
<% end %>
<%= f.submit%>
<% end %>
Try the following code:
<%= simple_form_for(#wine) do |f| %>
<div class="field">
<%= f.label :winemaker_id %>
<%= f.collection_select(:winemaker_id, Winemaker.all, :id, :name) %>
</div>
Have a look at http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select for more information.

Rails: Create Model and join table at the same time, has_many through

I have three Models:
class Question < ActiveRecord::Base
has_many :factor_questions
has_many :bigfivefactors, through: :factor_questions
accepts_nested_attributes_for :factor_questions
accepts_nested_attributes_for :bigfivefactors
end
class Bigfivefactor < ActiveRecord::Base
has_many :factor_questions
has_many :questions, through: :factor_questions
end
and my join-table, which holds not only the bigfivefactor_id and question_id but another integer-colum value.
class FactorQuestion < ActiveRecord::Base
belongs_to :bigfivefactor
belongs_to :question
end
Creating an new Question works fine, using in my _form.html.erb
<%= form_for(#question) do |f| %>
<div class="field">
<%= f.label :questiontext %><br>
<%= f.text_field :questiontext %>
</div>
<%= f.collection_check_boxes :bigfivefactor_ids, Bigfivefactor.all, :id, :name do |cb| %>
<p><%= cb.check_box + cb.text %></p>
<% end %>
This let's me check or uncheck as many bigfivefactors as i want.
But, as i mentioned before, the join model also holds a value.
Question:
How can I add a text-field next to each check-box to add/edit the 'value' on the fly?
For better understanding, i added an image
In the console, i was able to basically do this:
q= Question.create(questiontext: "A new Question")
b5 = Bigfivefactor.create(name: "Neuroticism")
q.bigfivefactors << FactorQuestion.create(question: q, bigfivefactor: b5, value: 10)
I also found out to edit my questions_controller:
def new
#question = Question.new
#question.factor_questions.build
end
But i have no idea how to put that into my view.
Thank you so much for your help!
Big Five Factors model considerations
It looks like your Bigfivefactors are not supposed to be modified with each update to question. I'm actually assuming these will be CMS controlled fields (such that an admin defines them). If that is the case, remove the accepts_nested_attributes for the bigfivefactors in the questions model. This is going to allow param injection that will change the behavior sitewide. You want to be able to link to the existing bigfivefactors, so #question.factor_questions.first.bigfivefactor.name is the label and #question.factor_questions.first.value is the value. Notice, these exist on different 'planes' of the object model, so there wont be much magic we can do here.
Parameters
In order to pass the nested attributes that you are looking for the paramater needs to look like this:
params = {
question: {
questiontext: "What is the average air speed velocity of a sparrow?",
factor_questions_attributes: [
{ bigfivefactor_id: 1, value: 10 },
{ bigfivefactor_id: 2, value: 5 } ]
}
}
Once we have paramaters that look like that, running Question.create(params[:question]) will create the Question and the associated #question.factor_questions. In order to create paramaters like that, we need html form checkbox element with a name "question[factor_questions_attributes][0][bigfivefactor_id]" and a value of "1", then a text box with a name of "question[factor_question_attributes][0][value]"
Api: nested_attributes_for has_many
View
Here's a stab at the view you need using fields_for to build the nested attributes through the fields for helper.
<%= f.fields_for :factor_questions do |factors| %>
<%= factors.collection_check_boxes( :bigfivefactor_id, Bigfivefactor.all, :id, :name) do |cb| %>
<p><%= cb.check_box + cb.text %><%= factors.text_field :value %></p>
<% end %>
<% end %>
API: fields_for
I'm not sure exactly how it all comes together in the view. You may not be able to use the built in helpers. You may need to create your own collection helper. #question.factor_questions. Like:
<%= f.fields_for :factor_questions do |factors| %>
<%= factors.check_box :_destroy, {checked => factors.object.persisted?}, '0','1' %> # display all existing checked boxes in form
<%= factors.label :_destroy, factors.object.bigfivefactor.name %>
<%= factors.text_box :value %>
<%= (Bigfivefactor.all - #question.bigfivefactors).each do |bff| %>
<%= factors.check_box bff.id + bff.name %><%= factors.text_field :value %></p> # add check boxes that aren't currently checked
<% end %>
<% end %>
I honestly know that this isn't functional as is. I hope the insight about the paramters help, but without access to an actual rails console, I doubt I can create code that accomplishes what you are looking for. Here's a helpful link: Site point does Complex nested queries

Notifications ala Facebook (database implementation)

I am wondering how Facebook implements their notifications system as I'm looking to do something similar.
FooBar commented on your status
Red1, Green2 and Blue3 commented on your photo
MegaMan and 5 others commented on your event
I can't have multiple notifications written into a single record, as eventually I will have actions associated with each notification. Also, in the view I'd like notifications to be rendered as expandable lists when a certain number of them exist for a single subject.
FooBar commented on your status (actions)
Red1, Green2 and Pink5 commented on your photo [+]
MegaMan and 3 others commented on your event [-]
MegaMan commented on your event (actions)
ProtoMan commented on your event (actions)
Bass commented on your event (actions)
DrWilly commented on your event (actions)
Cheers!
PS I am using postgres and rails BTW.
There are a number of ways to go about implementing this. It really depends on what kinds of notifications you want to cover and what information you need to collect about the notification to show it to the right user(s). If you are looking for a simple design that just covers notifications about posted comments, you could use a combination of polymorphic associations and observer callbacks:
class Photo < ActiveRecord::Base
# or Status or Event
has_many :comments, :as => :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commenter
belongs_to :commentable, :polymorphic => true # the photo, status or event
end
class CommentNotification < ActiveRecord::Base
belongs_to :comment
belongs_to :target_user
end
class CommentObserver < ActiveRecord::Observer
observe :comment
def after_create(comment)
...
CommentNotification.create!(comment_id: comment.id,
target_user_id: comment.commentable.owner.id)
...
end
end
What's happening here is that each photo, status, event etc. has many comments. A Comment obviously belongs to a :commenter but also to a :commentable, which is either a photo, status, event or any other model that you want to allow comments for. You then have a CommentObserver that will observe your Comment model and do something whenever something happens with the Comment table. In this case, after a Comment is created, the observer will create a CommentNotification with the id of the comment and the id of the user who owns the thing that the comment is about (comment.commentable.owner.id). This would require that you implement a simple method :owner for each model you want to have comments for. So, for example, if the commentable is a photo, the owner would be the user who posted the photo.
This basic design should be enough to get you started, but note that if you want to create notifications for things other than comments, you could extend this design by using a polymorphic association in a more general Notification model.
class Notification < ActiveRecord::Base
belongs_to :notifiable, :polymorphic => true
belongs_to :target_user
end
With this design, you would then 'observe' all your notifiables (models that you want to create notifications for) and do something like the following in your after_create callback:
class GenericObserver < ActiveRecord::Observer
observe :comment, :like, :wall_post
def after_create(notifiable)
...
Notification.create!(notifiable_id: notifiable.id,
notifiable_type: notifiable.class.name,
target_user_id: notifiable.user_to_notify.id)
...
end
end
The only tricky part here is the user_to_notify method. All models that are notifiable would have to implement it in some way depending on what the model is. For example, wall_post.user_to_notify would just be the owner of the wall, or like.user_to_notify would be the owner of the thing that was 'liked'. You might even have multiple people to notify, like when notifying all the people tagged in a photo when someone comments on it.
Hope this helps.
I decided to post this as another answer because the first was getting ridiculously long.
To render the comment notifications as expandable lists as you note in your
examples, you first collect the comments that have notifications for some target user (don't forget to add has_one :notification to the Comment model).
comments = Comment.joins(:notification).where(:notifications => { :target_user_id => current_user.id })
Note that the use of joins here generates an INNER JOIN, so you correctly exclude any comments that don't have notifications (as some notifications might have been deleted by the user).
Next, you want to group these comments by their commentables so that you can create an expandable list for each commentable.
#comment_groups = comments.group_by { |c| "#{c.commentable_type}#{c.commentable_id}"}
which will generate a hash like
`{ 'Photo8' => [comment1, comment2, ...], 'Event3' => [comment1, ...], ... }`
that you can now use in your view.
In some_page_showing_comment_notifications.html.erb
...
<ul>
<% #comment_groups.each do |group, comments| %>
<li>
<%= render 'comment_group', :comments => comments, :group => group %>
</li>
<% end %>
</ul>
...
In _comment_group.html.erb
<div>
<% case comments.length %>
<% when 1 %>
<%= comments[0].commenter.name %> commented on your <%= comment[0].commentable_type.downcase %>.
<% when 2 %>
<%= comments[0].commenter.name %> and <%= comments[1].commenter.name %> commented on your <%= comment[0].commentable_type.downcase %>.
<% when 3 %>
<%= comments[0].commenter.name %>, <%= comments[1].commenter.name %> and <%= comments[2].commenter.name %> commented on your <%= comment[0].commentable_type.downcase %>
<% else %>
<%= render 'long_list_comments', :comments => comments, :group => group %>
<% end %>
</div>
In _long_list_comments.html.erb
<div>
<%= comments[0].commenter.name %> and <%= comments.length-1 %> others commented on your <%= comments[0].commentable_type %>.
<%= button_tag "+", class: "expand-comments-button", id: "#{group}-button" %>
</div>
<%= content_tag :ul, class: "expand-comments-list", id: "#{group}-list" do %>
<li>
<% comments.each do |comment| %>
# render each comment in the same way as before
<% end %>
</li>
<% end %>
Finally, it should be a simple matter to add some javascript to button.expand-comments-button to toggle the display property of ul.expand-comments-list. Each button and list has a unique id based on the comment group keys, so you can make each button expand the correct list.
So I have kinda made a little something before the second answer was posted but got a bit too busy to compose and put it here. And I'm still studying if I did the right thing here, if it would scale or how it would perform overall. I would like to hear all your ideas, suggestions, comments to the way I have implemented this. Here goes:
So I first created the tables as typical polymorphic tables.
# migration
create_table :activities do |t|
t.references :receiver
t.references :user
t.references :notifiable
t.string :notifiable_type #
t.string :type # Type of notification like 'comment' or 'another type'
...
end
# user.rb
class User < ActiveRecord::Base
has_many :notifications, :foreign_key => :receiver_id, :dependent => :destroy
end
# notification.rb
class Notification < ActiveRecord::Base
belongs_to :receiver, :class_name => 'User'
belongs_to :user
belongs_to :notifiable, :polymorphic => true
COMMENT = 'Comment'
ANOTHER_TYPE = 'Another Type'
end
So it's just this. Then inserts quite typically like when a user does a certain type of notification. So what's new that I found for psql is ARRAY_AGG which is an aggregate function that groups a certain field into a new field as an array (but string when it gets to rails). So how I'm getting the records are now like this:
# notification.rb
scope :aggregated,
select('type, notifiable_id, notifiable_type,
DATE(notifications.created_at),
COUNT(notifications.id) AS count,
ARRAY_AGG(users.name) AS user_names,
ARRAY_AGG(users.image) as user_images,
ARRAY_AGG(id) as ids').
group('type, notifiable_id, notifiable_type, DATE(notifications.created_at)').
order('DATE(notifications.created_at) DESC').
joins(:user)
This outputs something like:
type | notifiable_id | notifiable_type | date | count | user_names | user_images | id
"Comment"| 3 | "Status" |[date]| 3 | "['first', 'second', 'third']" |"['path1', 'path2', 'path3']" |"[1, 2, 3]"
And then in my notifications model again, I have this methods which basically just puts them back to an array and removes the non-uniques (so that a name won't be displayed twice in a certain aggregated notification):
# notification.rb
def array_of_aggregated_users
self.user_names[1..-2].split(',').uniq
end
def array_of_aggregated_user_images
self.user_images[1..-2].split(',').uniq
end
Then in my view I have something like this
# index.html.erb
<% #aggregated_notifications.each do |agg_notif| %>
<%
all_names = agg_notif.array_of_aggregated_users
all_images = agg_notif.array_of_aggregated_user_images
%>
<img src="<%= all_images[0] %>" />
<% if all_names.length == 1 %>
<%= all_names[0] %>
<% elsif all_names.length == 2 %>
<%= all_names[0] %> and <%= all_names[1] %>
<% elsif all_names.length == 3 %>
<%= all_names[0] %>, <%= all_names[1] %> and <%= all_names[2] %>
<% else %>
<%= all_names[0] %> and <%= all_names.length - 1 %> others
<% end %>
<%= agg_notif.type %> on your <%= agg_notif.notifiable_type %>
<% if agg_notif.count > 1 %>
<%= set_collapsible_link # [-/+] %>
<% else %>
<%= set_actions(ids[0]) %>
<% end %>
<% end %>

Nested forms in rails - accessing attribute in has_many relation

I have a user and a profile model. One user can have many profiles. I need to access only one information from the profiles section (viz the phone number) in my user model during the user creation process. Hence I'm trying to get it done through attr_accessible. My user.rb looks like this.
has_many :profiles
attr_accessible :handle, :email, :password, :profile_mobile_number
attr_accessor : :profile_mobile_number
The problem that I'm facing is that when I try to call the getter method profile_mobile_number in a method in user.rb (the method is private, though I think it doesn't matter), I'm getting a null value. I use the following in my users/new.html.erb form
My question is what is the right way to do this? Should I use <% f.fields_for :profile do |ff| -%> or <% f.fields_for :profiles do |ff| -%> (notice that the second one is plural). When I use the plural :profiles, I don't even see the fields on the form. What am I missing here? And what is the tense that needs to be used in model user.rb? :profile_phone_number or :profiles_phone_number? Thanks.
You could do something like the following:
<% form_for #user, :url => { :action => "update" } do |user_form| %>
...
<% user_form.fields_for :profiles do |profiles_fields| %>
Phone Number: <%= profiles_fields.text_field :profile_mobile_number %>
<% end %>
<% end %>
But since you already have an association, then might as well use 'accepts_nested_attributes_for'
You should watch RailsCasts Nested Model Form.
thanks Ryan Bates great work.
http://apidock.com/rails/v3.2.8/ActionView/Helpers/FormHelper/fields_for
This api dock link list many Nested Attributes Examples including one-to-one, one-to-many. It's very helpful!
You can use 'accepts_nested_attributes_for' to do this; but there's a little trick in forms:
You must use the singular, and call fields_for for each profile, like this:
<% form_for #user do |f| -%>
<% #user.profiles.each do %>
<% f.fields_for :profile_attributes, profile do |ff| -%>
<% end %>
Notice that is :profile_attributes, instead of just :profile.

Rails Nested Object Form *_attributes

I'm using Rails 2.3.2, and trying to get a nested object form to work properly. I've narrowed my problem to the issue that Rails is not setting my nested form elements with the *_attributes required to initiate the accepts_nested_attributes_for processing.
My model code is:
class Person < Party
has_one :name, :class_name => "PersonName"
accepts_nested_attributes_for :name, :allow_destroy => true
end
class PersonName < ActiveRecord::Base
belongs_to :person
end
My view code looks like this (I'm using HAML):
%h3 New customer
= error_messages_for :person, :person_name, :name, :country
- form_for :person, :url => collection_url, :html => {:class => 'MainForm'} do |person_form|
- #person.build_name unless #person.name
- person_form.fields_for :name do |name_form|
= name_form.label :given_name, "First Name:"
= name_form.text_field :given_name
= name_form.label :family_name, "Last Name:"
= name_form.text_field :family_name
= hidden_field_tag :inviter_id, params[:inviter_id]
= hidden_field_tag :inviter_code, params[:inviter_code]
%p= submit_tag "Create"
= link_to 'Back', collection_url
Instead of params being:
{"person"=>{"name_attributes"=>{"given_name"=>"Fred", "family_name"=>"Flintstone"}}, ...}
I get:
{"person"=>{"name"=>{"given_name"=>"Fred", "family_name"=>"Flintstone"}}, ...}
As a result, I get a TypeMismatch exception. I've followed the documentation from Ryan Daigle. I've also followed the advice from this blog and the complex-forms-example.
Using Firebug, I went through my form and adjusted the name attribute of the input tags from name to name_attributes. This produced the params with name_attributes, and the create worked fine.
I'm stuck as I cannot figure out why my form is not producing the *_attributes form of the name.
Another thing I tried is I got the complex_form_example working in my environment. I've gone through every inch of the controller, models and views and compared it to my code. I cannot find what is different. I know this is something small, and would appreciate any help!
Thanks!
Post backs do not get routed to the right place
def new
#person = Person.new
end
<% form_for #person do |f| %>
<% f.fields_for :name_attributes do |p| %>
...
<% end %>
<% end %>
Post backs get routed to the right place
def new
#person = Person.new
#person.name = PersonName.new # << this allows fields_for :relation vs :relation_attributes
end
<% form_for #person do |f| %>
<% f.fields_for :name do |p| %>
...
<% end %>
<% end %>
No need to #person.name again in #create
Try to use an actual object for form_for:
form_for :person => form_for #person
I have just been struggling for about an hour with exactly the same problem!
Follow nowk's pattern for the new method in the controller, then put this in your view
<% form.fields_for :name, #person.name do |name_form| %>
<% end %>
Good luck if you try it, that's what worked for me.
Not sure why this isn't working for, but as a workaround, you could just use params[:name] in your controller#create method to update the person record.
person = Person.new(params[:person])
person.name << PersonName.new(params[:name])
Unfortunately, I still have not been able to figure out why this form wouldn't work with nested object forms. I stripped it down to the simplest data, started over using the complex-form-example as a start. I ended using the active_presenter to gather x-object data from the form. I'll revisit nested object forms sometime in the form. Thanks for your help.
Thought I would share my solution as it's slightly different - in my case I want the nested attributes to be dynamic.
In new action:
case params[:type]
when "clubber"
#account = resource.send "build_#{params[:type]}"
when "promoter"
#account = resource.send "build_#{params[:type]}"
when "company"
#account = resource.send "build_#{params[:type]}"
when "venue_owner"
flash[:notice] = 'We ask that venue owners register via the web. Thanks.'
redirect_to root_path and return
end
In my view:
= f.fields_for #account.class.name.downcase+'_attributes' do |form|
Pretty ghetto, but it works.

Resources