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_select
helper to show a select box containing your users:
<%= f.collection_select(:user_id, User.all, :id, :username, :prompt => true) %>
This renders something like:
<select name="url[user_id]">
<option value="">Please select</option>
<option value="1">One User</option>
<option value="2">Another User</option>
<option value="3">...</option>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.