我有两种模式:
第一个模型:
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)
第二种模式:
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)
现在我有一个表单,用于创建网址:
<%= 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 %>
为了增加用户友好性,我想用字段username更换字段user_id。需要采取哪些措施?
谢谢!
答案 0 :(得分:2)
您可以使用collection_select
帮助程序显示包含您的用户的选择框:
<%= f.collection_select(:user_id, User.all, :id, :username, :prompt => true) %>
这会呈现如下内容:
<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>