Here's an example table:
mysql> describe clients;
+--------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------------+------+-----+---------+-------+
| client_abbrv | varchar(5) | NO | PRI | | |
| client_name | varchar(50) | YES | | NULL | |
+--------------+-------------+------+-----+---------+-------+
To get this to work with Rails, I had to make a few small changes.
I made one small change in the view, which was setting the name of the primary key field. I changed "client_abbrv" to "id" in the form:
app/views/client/new.rhtml
<%= error_messages_for 'client' %>
<fieldset>
<legend>Add a Client
<% form_tag :action => "create" do %>
<p>
<label for="client_client_name">Client Name:
<%= text_field 'client', 'client_name' %>
</p>
<p>
<label for="client_id">Client Abbrv:
<%= text_field 'client', 'id' %>
</p>
<p>
<%= submit_tag 'Add' %>
</p>
<% end %>
</fieldset>
For the model, I had set the primary key with
set_primary_key
.app/models/clients.rb
class Client < ActiveRecord::Base
set_primary_key "client_abbrv"
end
Luckily, the table was already pluralized. If it had been "client," then I would have had to add this line:
def self.table_name() "client" end
For the controller, I had to change the create method:
app/controllers/client_controller.rb
def create
@client = Client.new
@client.id = params[:client][:id]
@client.client_name = params[:client][:client_name]
if @client.save
flash[:notice] = "Client was successfully created."
redirect_to :action => 'list'
else
render :action => 'new'
end
end
That replaced the old create method where I had the normal:
@client = Client.new(params[:client])
When using
set_primary_key
, you insert data using "id" and typically select data using the actual field name, "client_abbrv" in this case.Here's what the controller is doing for the create method:
dsparling-imbps-computer:~/my/rubydev/uclick-admin dsparlingimbp$ script/console
Loading development environment.
>> client = Client.new
=> #<Client:0x32b5e14 @new_record=true, @attributes={"client_name"=>nil}>
>> client.id = "abc"
=> "abc"
>> client.client_name = "ABC Company"
=> "ABC Company"
>> client.valid?
=> true
>> client.save
=> true
No comments:
Post a Comment