简体   繁体   English

我如何为belongs_to 关联播种?

[英]How do I seed a belongs_to association?

I would like to seed my Products and assign them to a specific User and Store .我想为我的Products播种并将它们分配给特定的UserStore

Product.rb产品.rb

class Product < ActiveRecord::Base

  belongs_to :user
  belongs_to :store

  def product_store=(id)
    self.store_id = id
  end
end

Note: Store belongs_to Business ( :business_name )注意: Store属于Business:business_name

Seed.rb种子文件

This is my basic setup:这是我的基本设置:

user = User.create(:username => 'user', :email => 'user2@email.com') 
store = Store.create(:business_name => 'store', :address => 'Japan')

I attempted these but they did not work:我尝试了这些,但它们不起作用:

# This gives random ID's ranging from 1 to 4425!?
user.products.create([{:name => "Apple", :product_store => Store.find_by_address('San Francisco, USA')}])

# This gives me undefined method 'walmart'.
 user.store.products.create([ {:name => "Apple"} ])

Is there a way to set the ID's so I can associate my Products to a Store and User ?有没有办法设置 ID,以便我可以将我的Products关联到StoreUser


UPDATE -更新 -

I have tried the answers below and still came out unsuccessful.我已经尝试了下面的答案,但仍然没有成功。 Does anyone know of another way to do this?有谁知道另一种方法来做到这一点?

Although it sounds like you found a workaround, the solution may be of interested to others.尽管听起来您找到了解决方法,但其他人可能会对解决方案感兴趣。

From your original seeds.rb从你原来的seeds.rb

user = User.create(:username => 'user', :email => 'user2@email.com')
store = Store.create(:business_name => 'store', :address => 'Japan')

Create the store创建商店

Store.create({
  user_id: user.id
  store_id: store.id
}, without_protection: true)

In the original code snipped "user" and "store" variables are declared.在原始代码中,声明了“user”和“store”变量。 The code assigns user_id / store_id (the model columns inferred by the belongs_to relationship in the Store model) to the id values that are present in the "user" and "store" variables.该代码将 user_id / store_id(由 Store 模型中的belongs_to 关系推断出的模型列)分配给存在于“user”和“store”变量中的 id 值。

"without_protection: true" turns off bulk assignment protection on the id fields. "without_protection: true" 关闭对 id 字段的批量赋值保护。 This is perfectly acceptable in a seeds file but should be used with extreme caution when dealing with user provided data.这在种子文件中是完全可以接受的,但在处理用户提供的数据时应格外小心。

Or alternatively create your stores.或者创建您的商店。

Then extract the correct one eg然后提取正确的一个,例如

store = Store.find_by_business_name('Test Store')

and then create it based on that eg然后根据那个创建它,例如

store.products.create(:product_name => "Product Test", :price => '985.93')

This will then set the relationship id for you,这将为您设置关系 ID,

If I'm not mistaken, you're just trying to do this.如果我没记错的话,你只是想这样做。

user = User.create(:username => 'usertwo', :email => 'user2@email.com') 
walmart = Store.create(:business_name => 'Walmart', :address => 'San Francisco, USA')

user.products.create(:name => 'Apple', :store => walmart)

Anything else required here that I'm not seeing?这里还有什么我没有看到的要求吗?

Try doing this尝试这样做

store_1 = Store.new(:business_name => 'Test Store',
:address => 'Test Address',
:phone_number => '555-555-555')

store_1.id = 1
store_1.save!

The trick is not to set the id within the hash as it is protected.诀窍是不要在散列中设置 id,因为它是受保护的。

Scott斯科特

What I did was update the particular products to a certain user, see this question:我所做的是将特定产品更新给某个用户,请参阅此问题:

Can I update all of my products to a specific user when seeding? 我可以在播种时将我的所有产品更新给特定用户吗?

Try this:尝试这个:

User.destroy_all
Product.destroy_all

user = User.create!([{:username => 'usertwo', :email =>'user2@email.com'},
{:username => 'userthree', :email => user3@email.com}])

user.each_with_index do |obj, index|
  Product.create!([{ :product_name => 'product #{index}', :user_id => obj.id }])
end

The table would look like this:该表将如下所示:

在此处输入图片说明 在此处输入图片说明

Here's how I prefer to seed an association in rails 6这是我更喜欢在 Rails 6 中建立关联的方式

@teacher = Teacher.new(name: "John")
@student = @teacher.build_student(name: "Chris")

@teacher.save!
@student.save!

You could just create a series of insert satements for this "seed migration", including the record Id for each user, store, product etc. You might have to update database sequences after this approach.您可以为此“种子迁移”创建一系列插入语句,包括每个用户、商店、产品等的记录 ID。您可能需要在此方法后更新数据库序列。

Another approach Create the initial records in you Rails app, through the GUI / web.另一种方法通过 GUI/web 在 Rails 应用程序中创建初始记录。 Then use something like Yaml-db.然后使用类似 Yaml-db 的东西。 So you can dump the data to a yaml file.因此,您可以将数据转储到 yaml 文件中。 You can now edit that file (if necessary) and use that same file to seed another instance of the db with "rake db:load"您现在可以编辑该文件(如有必要)并使用该文件以“rake db:load”为数据库的另一个实例做种

Either way.... You know the Ids will not be shifting around on you when these objects are created in the new db instance.无论哪种方式....您知道在新数据库实例中创建这些对象时,ID 不会在您身上移动。

I'm sure there are other ways to do this... Probably better ones, even.我敢肯定还有其他方法可以做到这一点......甚至可能更好。 Here is a link to a write-up I did a while back for using yaml_db to seed an oracle database http://davidbharrison.com/database_seeding_oracle这是我不久前使用 yaml_db 为 oracle 数据库提供种子的文章的链接http://davidbharrison.com/database_seding_oracle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 所属协会-我怎么称呼它? - belongs_to association — how do I call it? 如何在没有直接belongs_to的情况下设置一种“belongs_to:through”关联? - How do I set up a kind of “belongs_to :through” association without a direct belongs_to? 我如何使用searchlogic来搜索一个Emirates_to关联? - How do I use searchlogic to search on a belongs_to association? 我是否需要检查 Rails 中的belongs_to 关联中是否存在记录? - Do I need to check if record exist in a belongs_to association in Rails? 在Rails 5.1 中,如何为has_many 和belongs_to 关联编写finder 方法? - In Rails 5.1, how do I write a finder method for a has_many and then belongs_to association? 如何在不更改原始类的情况下替换belongs_to关联 - How do I replace a belongs_to association without changing the original class 如何在Rails 4.2中创建一个名为has_many和belongs_to的关联? - How do I create a named has_many and belongs_to association in Rails 4.2? 当关联对象被销毁时,如何将belongs_to关联设置为Nil - How do I set a belongs_to association to Nil when the associated object is destroyed 在Rails 3.1中如何为具有belongs_to关联的表单创建选择列表? - In Rails 3.1 How do I create a select list for a form that has a belongs_to association? 您如何为ActiveRecord所属关系声明一个可选条件? - How do you declare an optional condition for an ActiveRecord belongs_to association?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM