【问题标题】:Rails: Updating existing record with information from nested attributesRails:使用来自嵌套属性的信息更新现有记录
【发布时间】:2013-10-13 20:02:01
【问题描述】:

我在用户视图下有嵌套属性,并且想更新我的业务表中的现有记录信息,但是当我在嵌套属性中保存值时,它只是添加了一条新记录。

我有这个想法

<%= form_for @user, :html => {:multipart => true} do |f| %>
  <%= f.text_field :company_name %>
  <%= f.fields_for :businesses do |biz| %>
    <%= biz.text_field :street %>
    <%= biz.text_field :city %>
    <%= biz.text_field :zip %>
  <% end %>
<% end %>

然后我的控制器中有这个:

def edit
  @user = User.find(current_user.id)
  @user.businesses.new if @user.businesses.empty?
end 

def update
  @biz = Business.find_or_create_by_name(params[:user][:company_name])
end

因此,除了 Users 表之外,更新方法还允许将“company_name”(不在嵌套属性中)保存在 Business 表中。但现在我想获取街道、城市和邮编,即嵌套属性,并与company_name's 记录一起保存在业务记录中。

我想我必须获取企业 ID,然后根据该 ID 更新记录,不知道如何?

我可以做类似的事情

def update
  @biz = Business.find_or_create_by_name(params[:user][:company_name])
  @biz.id #to get the id of the business when updating
end

这就是我卡住的地方,如何将这些值保存在@biz.id 的记录中?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2 nested-attributes


    【解决方案1】:

    找到或创建 @biz 对象后,只需更新它:

    def update
      @biz = Business.find_or_create_by_name(params[:user][:company_name])
      @biz.update_attributes(params[:businesses])
    end
    

    【讨论】:

    • 它似乎没有更新现有业务。它更新了创建的“新”记录
    • 它将更新@biz 变量中的任何内容。如果没有 Business 与 name 字段匹配 params[:user][:company_name] 然后它将创建一个新的 Business 实例 name = params[:user][:company_name] 然后更新它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多