=#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
Host |
Hostname |
IP |
<% @hosts.each do |host| %>
<%=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 %> |
<% 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?