Rails 4 - simple_form 和从 url 预填充字段

jak*_*ork 4 parameters ruby-on-rails simple-form ruby-on-rails-4

我正在使用 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' %>
Run Code Online (Sandbox Code Playgroud)

PS - 我一边做这件事,一边在 Spotify 上听 GusGus 的新专辑,这对我很有帮助。:)

mpo*_*lov 5

最佳实践是不直接使用参数而是使用 ActiveRecord 对象预填充表单。例如,您有一个 AR 课程:

class Party < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

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
Run Code Online (Sandbox Code Playgroud)

然后在您的编辑视图中:

<%= simple_form_for @party do |f| %>
  <%= f.association :event %>
  <%= f.association :user %>
<% end %>
Run Code Online (Sandbox Code Playgroud)