# Update joined table

**URL:** <https://www.ruby-forum.com/t/update-joined-table/179735>\
**Category:** Rails\
**Created:** [December 2, 2009, 10:01pm UTC](https://www.ruby-forum.com/t/update-joined-table/179735 "2009-12-02T22:01:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![duke](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/e8c25b/32.png) [@duke](https://www.ruby-forum.com/u/duke)\
**Post date:** [December 2, 2009, 10:01pm UTC](https://www.ruby-forum.com/t/update-joined-table/179735/1 "2009-12-02T22:01:17Z")

</div>

=#select \* from hosts;  
id | hostname |  
----±---------+  
1 | foo |  
2 | bar |  
3 | hoge |

=# select \* from ipaddresses;  
id | host\_id | address |  
----±--------±------------+  
1 | 1 | 192.168.1.1 |  
2 | 2 | 192.168.1.2 |  
3 | 3 | 192.168.1.3 |

Model  
host.rb  
class Host \< ActiveRecord::Base  
has\_one :ipaddress  
end

ipaddress.rb  
class Ipaddress \< ActiveRecord::Base  
belongs\_to :host  
end

## View index.html.erb

# Listing hosts

\<% @hosts.each do |host| %\>

\<% end %\> ------------------------------------------------------ I can see host.hostname and host.ipaddress.address.
## I have a problem for updating ipaddress.address. hosts\_controller.rb

def edit  
@host = Host.find(params[:id], :joins =\> “LEFT JOIN ipaddresses on  
hosts.id=ipaddresses.host\_id”, :select =\> “hosts.\*,  
ipaddresses.address”)  
end

def update  
@host = Host.find(params[:id], :joins =\> “LEFT JOIN ipaddresses on  
hosts.id=ipaddresses.host\_id”, :select =\> “hosts.\*,  
ipaddresses.address”)  
@host.ipaddress.address = params[:address]  
@host.ipaddress.save

```
respond_to do |format|
  if @host.update_attributes(params[:host])
    flash[:notice] = 'Host was successfully updated.'
    format.html { redirect_to(@host) }
    format.xml { head :ok }
  else
    format.html { render :action => "edit" }
    format.xml { render :xml => @host.errors, :status =>

```

## :unprocessable\_entity } end end end

## View edit.html.erb

# Editing host

\<% form\_for(@host) do |f|%\>  
\<%= f.error\_messages %\>

\<%= f.label :host\_id %\>  
 \<%= f.text\_field :host\_id %\>

\<%= f.label :hostname %\>  
 \<%= f.text\_field :hostname %\>

\<%= f.label :IP %\>  
 \<%= f.text\_field :address %\>

\<%= f.submit 'Update' %\>

\<% end %\>
## \<%= link\_to ‘Show’, @host %\> | \<%= link\_to ‘Back’, hosts\_path %\>

If I use @host.ipaddress.address = ‘192.168.1.10’, ipaddress.address is  
updated,  
but params[:address] is used, nil is updated to ipaddress.address,  
and rails shows ‘Host was successfully updated.’.  
Why?

| Host | Hostname | IP |
| --- | --- | --- |
| \<%=h host.host\_id %\> | \<%=h host.hostname %\> | \<%=h host.ipaddress.address %\> | \<%= link\_to 'Show', host %\> | \<%= link\_to 'Edit', edit\_host\_path(host) %\> | \<%= link\_to 'Destroy', host, :confirm =\> 'Are you sure?', :method =\> :delete %\> |
