I’ve two models:
The first model:
class Url < ActiveRecord::Base
attr_accessible :code, :target, :user_id, :user
belongs_to :user, :dependent => :destroy
end
rails console
1.9.3p125 :001 > Url
=> Url(id: integer, user_id: integer, code: string, target: string, created_at: datetime, updated_at: datetime)
The second model:
class User < ActiveRecord::Base
attr_accessible :description, :status, :username
has_many :urls
validates :username,
:presence => true,
:uniqueness => true
def to_s
username
end
end
rails console
1.9.3p125 :002 > User
=> User(id: integer, username: string, status: integer, description: text, created_at: datetime, updated_at: datetime)
Now i have a form, for creating an url:
<%= form_for(@url) do |f| %>
<% if @url.errors.any? %>
<div id="error_explanation">
<h2><%= @url.errors.count %> Error(s):</h2>
<ul>
<% @url.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :user_id %><br />
<%= f.text_field :user_id %>
</div>
<div class="field">
<%= f.label :code %><br />
<%= f.text_field :code %>
</div>
<div class="field">
<%= f.label :target %><br />
<%= f.text_field :target %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
To increase the user-friendliness I want to exchange the field user_id with the field username. What steps are necessary to do?
Thanks!
You could use the
collection_selecthelper to show a select box containing your users:This renders something like: