【问题标题】:Database entry of Select tag selection by user goes as NULL. How do I put selection ID up there in database?用户选择标签选择的数据库条目为 NULL。如何将选择 ID 放在数据库中?
【发布时间】:2015-03-23 18:55:37
【问题描述】:

如何将选择 ID 放入数据库中?

我对 ruby​​ on rails 有点陌生。我正在尝试设置一个表单,该表单具有从出生地数据库填充的出生地组合框。

数据库:出生地

Id  birthplace  created_at  updated_at
1   New York    -------------   -------------
2   London      -------------   -------------

表单提交应以用户在组合框中选择的 id 进入员工数据库。 例如,用户将 Nick 与出生地组合框选择 New York 放在一起,那么它应该是这样的

数据库:员工

Id  name        birthplace  created_at  updated_at
1   Nick        1       -------------   -------------

代码:new.html.erb `

<%= form_for(@employees) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :birthplace %>
<%= select("post", :birthplace, @birthplace.collect {|p| [ p.birthplace, p.id ]}, {:include_blank => 'Please Select'} )%>
<%= f.submit "Save", class: "btn btn-large btn-primary" %>
<% end %>

'

代码:employees_controller.rb

Def new
@employees =Employee.new
    @birthplace = Birthplace.all
  end

  def create
    @birthplace = Birthplace.all
@employees = Employee.new (params[:employees])
    if @student.save

 flash[:success]= "Welcome to AVIS!"
        render 'new'
    else
        flash[:success]= "Some Errors!"
        render 'new'
    end
  end

【问题讨论】:

  • 不是 student.save 而是 employees.save
  • 你试过把@student.save改成@employees.save
  • 是的,实际上我在发布问题时打错了。

标签: ruby-on-rails


【解决方案1】:

尝试在EmployeeBirthplace 之间创建关联。

class Employee < ActiveRecord::Base
  belongs_to :birthplace
end

还有你的表格:

<%= form_for(@employees) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :birthplace %>
<%= f.select(:birthplace, Birthplace.all.collect{|p| [ p.birthplace, p.id ]}, {:include_blank => 'Please Select'}) %>
<%= f.submit "Save", class: "btn btn-large btn-primary" %>
<% end %>

现在您可以直接在控制器中使用表单中的信息。

def new
  @employee = Employee.new
end

def create
  @employee = Employee.new params[:employee]
  if @employee.save
    flash[:success]= "Welcome to AVIS!"
    render 'new'
  else
    flash[:error]= "Some Errors!"
    render 'new'
  end
end

使用强参数https://github.com/rails/strong_parameters

def new
  @employee = Employee.new
end

def create
  @employee = Employee.new employee_params
  if @employee.save
    flash[:success]= "Welcome to AVIS!"
    render 'new'
  else
    flash[:error]= "Some Errors!"
    render 'new'
  end
end

private

def employee_params
  params.require(:employee).permit(:name, :birthplace_id)
end

【讨论】:

  • 你可以让它在没有关联的情况下工作,方法是让你的参数像param[:employee][:birthplace_id]
  • 谢谢。但是你能否提供更多关于强参数的信息,我有点卡在那里。没有强大的参数,它工作得很好。
  • 我添加了强参数案例。它应该与 :birthplace_id 一起使用,但如果不让我知道 HTML 是如何生成的,那么我可以有更好的洞察力。
猜你喜欢
  • 1970-01-01
  • 2013-10-28
  • 2018-04-11
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
相关资源
最近更新 更多