我正在使用 simple_form 并且我想在我的表单中预填充几个字段。在表单的链接中,我将几个值传递给 URL 中的参数。当我尝试将值传递给整数或关联字段时,麻烦就来了。在任何一种情况下,该字段都不会预先填充。
下面的示例...前两个字段填充良好,但我不得不强制它们为文本字段。也许可以将 url 中的字符串推送到字段中,但理想情况下,我可以使用整数 (f.input) 或关联 (f.association)。后两个字段不会从 URL 中提取参数值。
有任何想法吗?提前致谢!
注意 - 这是用于在数据库中生成新记录,而不是用于编辑现有记录。
URL: http://localhost:5000/list/new?event_id=4&user_id=11
<!-- These two fields pre-populate -->
<%= f.text_field :event_id, :value => params[:event_id] %>
<%= f.text_field :user_id, :value => params[:user_id] %>
<br>
<!-- These two fields do NOT pre-populate -->
<%= f.association :event_id, :value => params[:event_id] %>
<%= f.input :event_id, :value => params[:event_id], label: 'Event' %>
PS - 我正在 Spotify 上听 GusGus 的新专辑,同时我也在做这件事,这很有帮助。 :)
最佳答案
最佳实践是不直接使用参数而是使用 ActiveRecord 对象预填充表单。
例如,您有一个 AR 类:
class Party < ActiveRecord::Base
belongs_to :event
belongs_to :user
end
然后在您的 Controller 中:
def new
@party = Party.new(party_params)
end
# use strong params to make your parameter more secure;)
def party_params
params.permit(:event_id, :user_id)
end
然后在您的编辑 View 中:
<%= simple_form_for @party do |f| %>
<%= f.association :event %>
<%= f.association :user %>
<% end %>
关于ruby-on-rails - Rails 4 - simple_form 和来自 url 的预填充字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24416087/