【问题标题】:Rails nested attributes with existing records带有现有记录的 Rails 嵌套属性
【发布时间】:2021-07-17 08:52:28
【问题描述】:

我正在尝试用通常的方式处理嵌套属性:

型号:

class InventoryItem < ApplicationRecord
  belongs_to :location

  accepts_nested_attributes_for :location
end

表格:

  <div class="field">
    <%= form.fields_for :location do |location| %>
      <%= location.label :location_name %>
      <%= location.text_field :name %>
    <% end %>
  </div>

控制器:

  def new
    @inventory_item = InventoryItem.new
    @inventory_item.build_location
  end

  def inventory_item_params
    params.require(:inventory_item).permit(:location_id, location_attributes:[:name])
  end

我的问题是,如果Location 存在,我希望新的InventoryItem 与之关联。 如果Location 存在name,我现在不知道如何重建InventoryItem 和Location 之间的关联。控制器中的:@inventory_item.build_location 总是在创建一个新的Location。

提前致谢

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    accepts_nested_attributes_for :location 为您的InventoryItem 模型添加了一个方法:location_attributes=。

    你对这个方法有一个特殊的限制,所以你需要在inventory_item.rb中覆盖它,像这样:

    #inventory_item.rb
    def location_attributes=(attrs)
      begin
        self.location_id = Location.find_by!(name: attrs[:name])
      rescue ActiveRecord::RecordNotFound
        super
      end
    end
    

    【讨论】:

    • 谢谢@les-nightingill 是一个好的开始,我改成了self.location。你能推荐我一些书籍或资源来更好地了解这些内部知识吗?提前致谢
    • @JohnFadria 我真的没有什么 Rails 书可以推荐。仔细研究 Rails 文档,大部分答案都在那里!
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多