【问题标题】:associate one record to another via rails console通过 rails 控制台将一条记录关联到另一条记录
【发布时间】:2017-04-19 03:46:16
【问题描述】:

我是 RoR 的新手,我正在练习模型和关联。

我通过 rails 控制台创建了一些用户和订单:

order = Order.create(body: "i'm a new order")
user = User.create(name: "Borja")

我想知道如何将具有特定 id 的帖子分配给具有特定 id 的用户(例如, post(2) 属于 user(1) ),所以我可以使用 rails 控制台检查这种关系的方法.

谢谢!

models/user.rb >

class User < ApplicationRecord
  has_many :orders
end

模型/post.rb >

class Order < ApplicationRecord
  belongs_to :user, optional: true
end

【问题讨论】:

  • user.posts.create()Post.create(user_id: user.id) 其中user 可以是user = User.first

标签: ruby-on-rails model-view-controller associations models


【解决方案1】:

你是故意把这个类命名为Order,还是弄错了?

您需要将文件名更改为order.rb,或者您需要将模型名称更改为Post

models/user.rb

class User < ApplicationRecord
  has_many :posts
end

models/post.rb

 class Post < ApplicationRecord
   belongs_to :user, optional: true
 end

在用户范围内创建帖子

user = User.find(1)
user.posts.create(body: "some text") # user id will be passed automatically

# or

user = User.find(1)
Post.create(user_id: user.id, body: "some text")

【讨论】:

    【解决方案2】:
    • 首先,您要查找用户或创建用户(如果用户不存在)。
    • 然后你要查找或创建一个帖子(如果它不存在)
    • 然后您想调用正确的方法将用户与帖子相关联。

    想想里面的methods that User class gains when a has_many association is declared

    以上不是将用户与帖子关联的最佳方式,但它是最低限度的,并且会让您考虑关联工作。

    PS:请确保您的问题格式正确。这样会有更多的人有动力去回答。

    祝你好运!

    【讨论】:

    • 谢谢!我去看看:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2012-10-24
    • 2015-04-25
    • 1970-01-01
    相关资源
    最近更新 更多