【问题标题】:Id is not associated after seeding with nested attributes on ruby on rails?在使用 ruby​​ on rails 上的嵌套属性播种后,ID 没有关联?
【发布时间】:2016-06-22 02:24:29
【问题描述】:

为什么我播种后space_listing_id是空的?

我的模型上有这个。

 class SpaceListing < ActiveRecord::Base
  belongs_to :user
  has_many :images, dependent: :destroy
  has_many :bookings, dependent: :destroy
  has_many :favorites
  has_many :reviews, dependent: :destroy
  accepts_nested_attributes_for :images, allow_destroy: true

 validates :title, presence: true
 validates :description, presence: true
 validates :day_rent, presence: true
 validates :monthly_rent, presence: true
 validates :space_type, presence: true
 validates :environment_type, presence: true
 validates :size_length, presence: true
 validates :size_width, presence: true
 validates :size_height, presence: true
end

这就是我的seed.rb 拥有的:

SpaceListing.create!([
  {
user_id: 1,
title: "Hipster Vest",
description: "Hipster's favorite spot",
street_number: "10",
route: "Hipster Street",
city: "San Francisco",
state: "CA",
zip_code: "94108",
country: "United States",
space_type: "Garage",
environment_type: "Outdoor",
monthly_rent: 100,
day_rent: 3,
size_width: 10,
size_height: 10,
size_length: 10,
latitude: 37.7875474,
longitude: -122.4049517,
images_attributes: [
   {image_url: "https://media.giphy.com/media/26BRwxtVBt8dWEuGs/giphy.gif",
    space_listing_id: },
   {image_url: "https://media.giphy.com/media/l3UcgEIw80eyb36kU/giphy.gif"}
  ]
 }
])

【问题讨论】:

    标签: ruby-on-rails nested-attributes seed


    【解决方案1】:

    accepts_nested_attributes 创建一个新属性,该属性可以传递给 ActiveRecord 方法,例如 .create 和 .update。在您的情况下,该属性将被称为:images_attributes

    以下代码将解决您的问题。

    SpaceListing.create!([
      {
        user_id: 1,
        title: "Hipster Vest",
        description: "Hipster's favorite spot",
        street_number: "10",
        route: "Hipster Street",
        city: "San Francisco",
        state: "CA",
        zip_code: "94108",
        country: "United States",
        space_type: "Garage",
        environment_type: "Outdoor",
        monthly_rent: 100,
        day_rent: 3,
        size_width: 10,
        size_height: 10,
        size_length: 10,
        latitude: 37.7875474,
        longitude: -122.4049517,
        images_attributes: [
          { image_url:  "https://media.giphy.com/media/26BRwxtVBt8dWEuGs/giphy.gif"},
          { image_url:  "https://media.giphy.com/media/l3UcgEIw80eyb36kU/giphy.gif"}
        ]
      }
    ])
    

    更新: 你似乎已经更新了这个问题。我会回答的。您不需要在属性哈希中包含:space_listing_id。使用我上面发布的代码,Rails 将自动关联记录并填充 :space_listing_id 键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-23
      • 2014-08-22
      • 2014-04-03
      相关资源
      最近更新 更多