Rails 4表单 - 向现有记录添加新输入

时间:2014-08-18 19:27:39

标签: ruby-on-rails

我有一个表单,用户输入的个人资料信息保存在用户模型中。我需要在稍后阶段(在不同的页面上)从用户收集另一条信息。如何收集此信息并将其附加到现有用户记录?

这是我的表单代码,其中包含用户需要的一个额外输入。当我点击提交时,它运行没有错误,但新字段没有保存在我的模型中。我运行了迁移以将字段添加到模型中。

<%= form_for @user, html: { method: :put }) do |f| %>

 <div class="form-group">
  <%= f.label :what_is_your_favorite_color %>
  <%= f.text_field :color, class:"form-control" %>
 </div>

 <div class="form-group">
    <%= f.submit "Submit", class:"btn btn-primary" %>
 </div>

<% end %>

我的控制器更新方法目前是空白的..你能告诉我更新方法应该是什么样的吗?用户已登录,因此我需要找到该用户记录(可能是id列?)并将新输入写入或更新到模型中。

def update
   ??    
end

1 个答案:

答案 0 :(得分:1)

首先需要获取你的记录,把它传递给params hash,而Rails将完成其余的工作。

def update
  @record = Record.find(params[:id])
  if @record.update(record_params)
    redirect_to @record
  else
    render :edit
  end
end

如果您使用的是Rails 4,则需要考虑strong_parameters。因此,将新属性添加到允许的属性中。

  def record_params
    params.require(:record).permit(:color, :and, :other, :attributes, :go, :here)
  end

上面的代码假定记录ID将在params哈希中,或者换句话说,您正在使用RESTful路由。如果不是,您可能希望从会话中传入id(如果这是,如您所说,用户记录,并且您正在使用Devise)。

def update
  @record = Record.find(current_user)
  # ... the rest should be the same
end
相关问题