【问题标题】:Ruby on Rails - Select in form helper always saves first optionRuby on Rails - 在表单助手中选择始终保存第一个选项
【发布时间】:2017-10-03 21:51:00
【问题描述】:

我正在开展一个项目,在该项目中,创建用户后应将其添加到团队中。创建新团队时,团队列表会更新。

但是,每次我保存用户时,团队都会保存为下拉菜单中的第一项。

  <%= f.label :team %>
  <%= f.select :team, {}, {}, id: :user_team do %>
      <% @teams.each do |team| %>
        <%= content_tag :option, team.name, value: team.id %>
      <% end %>
  <% end %>

控制器:

def create
team = Team.find_by(params[:user_team]).id

user = User.new(user_params)
user.team_id = team

if (params[:user_admin] == '0')
    user.admin = 'false'
else
    user.admin = 'true'
end

if (user.valid?)
    user.save
    redirect_to "/users/#{user.id}"
else
    flash[:notice] = user.errors.full_messages
    redirect_to '/users/new'
end

结束

def user_params
  params.require(:user).permit(:first_name, :last_name, :username, 
  :password, :password_confirmation, :admin, :team)
end

【问题讨论】:

  • 你能展示你的控制器、渲染的表单和提交的参数吗?
  • 第二个呈现的形式。我的猜测是 &lt;%= content_tag :option, team.name, value: team.id %&gt; 可能没有按照您的想法做,或者您需要提示或 include_blank 参数。

标签: ruby-on-rails actionview


【解决方案1】:

这是在黑暗中的一个镜头,但您可以尝试添加一个占位符元素,或者通过将include_blank: true 传递给您选择的 ERB 标记,或者通过提供一个像这样的空值选项:&lt;option value=""&gt;Select One&lt;/option&gt;。前者将是更“rails-y”的方式,如此处所述:https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

在此基础上,我认为您的选择始终默认选择第一个元素,因为没有提示或占位符。如果是这种情况,那么如果您不主动更改它,那么它每次都会发送第一个选项的值。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多