# Problem passing id to another model

**URL:** <https://www.ruby-forum.com/t/problem-passing-id-to-another-model/177463>\
**Category:** Rails\
**Created:** [October 18, 2009, 1:17am UTC](https://www.ruby-forum.com/t/problem-passing-id-to-another-model/177463 "2009-10-18T01:17:22Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![ryan8720](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/c6cbf5/32.png) [@ryan8720](https://www.ruby-forum.com/u/ryan8720)\
**Post date:** [October 18, 2009, 1:17am UTC](https://www.ruby-forum.com/t/problem-passing-id-to-another-model/177463/1 "2009-10-18T01:17:22Z")

</div>

I have a rails application that models a house. house contains rooms  
and rooms have nested attributes for light and small\_appliance. I have  
a calculator controller, which is how end users will access the  
application.

My problem is that I can’t get the partial for adding rooms to submit  
correctly from calculator. The initial page lets the user enter house  
information, which is saved using save\_house when submit is clicked.  
This also redirects the user to the add\_rooms page, where they can add  
rooms to the house.

add\_rooms displays correctly, but when I click submit, I get this  
error:

* * *

RuntimeError in Calculator#add\_room

Showing app/views/calculator/add\_rooms.html.erb where line #2 raised:

Called id for nil, which would mistakenly be 4 – if you really wanted  
the id of nil, use object\_id

Extracted source (around line #2):

1:

  
2: 

House id is \<%= @house.id %\>

  
3:  
4: 
### Your rooms:
  
5: \<% if @house.rooms %\>

RAILS\_ROOT: C:/Users/ryan/Downloads/react  
Application Trace | Framework Trace | Full Trace

C:/Users/ryan/Downloads/react/app/views/calculator/add\_rooms.html.erb:  
2:in `_run_erb_app47views47calculator47add_rooms46html46erb' C:/Users/ryan/Downloads/react/app/controllers/calculator_controller.rb: 36:in`add\_room’  
C:/Users/ryan/Downloads/react/app/controllers/calculator\_controller.rb:  
33:in `add\_room’

* * *

This is odd to me, because when add\_rooms first renders, it shows the  
house\_id. I don’t understand why it isn’t passed after the form is  
submitted.

Here’s the code:

* * *

#app/models/room.rb

class Room \< ActiveRecord::Base

# schema { name:string, house\_id:integer }

belongs\_to :house  
has\_many :lights, :dependent =\> :destroy  
has\_many :small\_appliances, :dependent =\> :destroy  
validates\_presence\_of :name  
accepts\_nested\_attributes\_for :lights, :reject\_if =\> lambda { |a|  
a.values.all?(&:blank?) }, :allow\_destroy =\> true  
accepts\_nested\_attributes\_for :small\_appliances, :reject\_if =\>  
lambda { |a| a.values.all?(&:blank?) }, :allow\_destroy =\>  
true  
end

* * *

#app/models/house.rb

class House \< ActiveRecord::Base  
has\_many :rooms

# validation code not included

def add\_room(room)  
rooms \<\< room  
end

end

* * *

#app/controllers/calculator\_controller.rb

class CalculatorController \< ApplicationController  
def index  
end

def save\_house  
@house = House.new(params[:house])  
respond\_to do |format|  
if @house.save  
format.html { render :action =\> ‘add\_rooms’, :id =\> @house }  
format.xml { render :xml =\> @house, :status  
=\> :created, :location =\> @house }  
else  
format.html { render :action =\> ‘index’ }  
format.xml { render :xml =\> @house.errors, :status  
=\> :unprocessable\_entity }  
end  
end  
end

def add\_rooms  
@house = House.find(params[:id])  
@rooms = Room.find\_by\_house\_id(@house.id)

rescue ActiveRecord::RecordNotFound  
logger.error(“Attempt to access invalid house #{params[:id]}”)  
flash[:notice] = “You must create a house before adding rooms”  
redirect\_to :action =\> ‘index’  
end

def add\_room  
@room = Room.new(params[:room])  
@house = @room.house

```
respond_to do |format|
  if @room.save
    flash[:notice] = "Room \"#removed_email_address@domain.invalid}\" was successfully

```

added."  
format.html { render :action =\> ‘add\_rooms’ }  
format.xml { render :xml =\> @room, :status  
=\> :created, :location =\> @room }  
else  
format.html { render :action =\> ‘add\_rooms’ }  
format.xml { render :xml =\> @room.errors, :status  
=\> :unprocessable\_entity }  
end  
end  
rescue ActiveRecord::RecordNotFound  
logger.error(“Attempt to access invalid house #{params[:id]}”)  
flash[:notice] = “You must create a house before adding a room”  
redirect\_to :action =\> ‘index’  
end

def report  
flash[:notice] = nil  
@house = House.find(params[:id])  
@rooms = Room.find\_by\_house\_id(@house.id)  
rescue ActiveRecord::RecordNotFound  
logger.error(“Attempt to access invalid house #{params[:id]}”)  
flash[:notice] = “You must create a house before generating a  
report”  
redirect\_to :action =\> ‘index’  
end

end

* * *

#app/views/calculator/add\_rooms.html.erb

House id is \<%= @house.id %\>

### Your rooms:
 \<% if @house.rooms %\> 
 \<% for room in @house.rooms %\> - \<%= h room.name %\> has \<%= h room.number\_of\_bulbs %\> \<%= h room.wattage\_of\_bulbs %\> watt bulbs, in use for \<%= h room.usage\_hours %\> hours per day. 
 \<% end %\> 
 \<% else %\> 

You have not added any rooms yet

 \<% end %\>

\<%= render :partial =\> ‘rooms/room\_form’ %\>

  

\<%= button\_to “Continue to report”, :action =\> “report”, :id =\> @house  
%\>

* * *

#app/views/rooms/\_room\_form.html.erb

\<% form\_for :room, @house.rooms.build, :url =\> { :action  
=\> :add\_room } do |form| %\>  
\<%= form.error\_messages %\>

\<%= form.label :name %\>  
 \<%= form.text\_field :name %\>

### Lights
 \<% form.object.lights.build if form.object.lights.empty? %\> \<% form.fields\_for :lights do |light\_form| %\> \<%= render :partial =\> "light", :locals =\> { :form =\> light\_form } %\> \<% end %\> 

\<%= add\_child\_link "[+] Add new light", form, :lights %\>

### Small Appliances
 \<% form.object.small\_appliances.build if form.object.small\_appliances.empty? %\> \<% form.fields\_for :small\_appliances do |sm\_appl\_form| %\> \<%= render :partial =\> "small\_appliance", :locals =\> { :form =\> sm\_appl\_form } %\> \<% end %\> 

\<%= add\_child\_link "[+] Add new small appliance", form, :small\_appliances %\>

\<%= form.submit "Submit" %\>

\<% end %\>
* * *

#application\_helper.rb

module ApplicationHelper  
def remove\_child\_link(name, form)  
form.hidden\_field(:\_delete) + link\_to\_function(name, “remove\_fields  
(this)”)  
end

def add\_child\_link(name, form, method)  
fields = new\_child\_fields(form, method)  
link\_to\_function(name, h(“insert\_fields(this, “#{method}”, “#  
{escape\_javascript(fields)}”)”))  
end

def new\_child\_fields(form\_builder, method, options = {})  
options[:object] ||=  
form\_builder.object.class.reflect\_on\_association(method).klass.new  
options[:partial] ||= method.to\_s.singularize  
options[:form\_builder\_local] ||= :form  
form\_builder.fields\_for(method, options[:object], :child\_index =\>  
“new\_#{method}”) do |form|  
render(:partial =\> options[:partial], :locals =\> { options  
[:form\_builder\_local] =\> form })  
end  
end  
end

* * *

Thanks,  
Ryan

---

<div class="post-metadata">

**Author:** ![ryan8720](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/c6cbf5/32.png) [@ryan8720](https://www.ruby-forum.com/u/ryan8720)\
**Post date:** [October 18, 2009, 1:37am UTC](https://www.ruby-forum.com/t/problem-passing-id-to-another-model/177463/2 "2009-10-18T01:37:16Z")

</div>

On Oct 18, 12:15 am, ryan8720 [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> This is odd to me, because when add\_rooms first renders, it shows the  
> house\_id. I don’t understand why it isn’t passed after the form is  
> submitted.

Well from a cursory glance of your form, @house is nil because nowhere  
do you pass an :id parameter, so you end up doing @house = House.find  
(nil)  
If I’m reading correctly the first time the form is rendered you’re in  
the add\_room action so house ends up being derived from params[:room]  
[:house\_id] but in add\_rooms @house is retrieved differently.

Fred

---

<div class="post-metadata">

**Author:** ![ryan8720](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/c6cbf5/32.png) [@ryan8720](https://www.ruby-forum.com/u/ryan8720)\
**Post date:** [October 18, 2009, 5:48am UTC](https://www.ruby-forum.com/t/problem-passing-id-to-another-model/177463/3 "2009-10-18T05:48:18Z")

</div>

Hi Ryan,

The problem is you have’t actually passed the house id to the room  
because

House id is \<%= @house.id %\>

just displays the house id to that page. But it won’t be submitted  
with the form  
If I am getting right you have a relationship in house model like  
has\_many :rooms

ok  
Let me explain that to get the house id in controller the house.id  
must be submitted to the controller  
You can do this by two ways

1. Submitting house.id via hidden field  
use \<%= hidden\_field :house\_id%\>

Note to get this running it must be set when building new room object  
build using  
@house.rooms.build() OR  
Room.new(:house\_id =\> @house.id)

If this one didn’t work contact me at  
removed\_email\_address@domain.invalid or

blog.railsjaipur.in

I’ll tell you a second solution.

---

<div class="post-metadata">

**Author:** ![ryan8720](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/c6cbf5/32.png) [@ryan8720](https://www.ruby-forum.com/u/ryan8720)\
**Post date:** [October 19, 2009, 4:03am UTC](https://www.ruby-forum.com/t/problem-passing-id-to-another-model/177463/4 "2009-10-19T04:03:23Z")

</div>

Thanks pankaj88, that worked nicely.
