简体   繁体   English

Rails 4-通过has_many创建记录

[英]Rails 4 - Create record with has_many through

In my project i have something like this: 在我的项目中,我有这样的事情:

class User < ActiveRecord::Base
  has_many  :roles
  has_many  :websites, through: :roles
end

class Website < ActiveRecord::Base
  validates                 :name, presence: true
  has_many                  :roles
  has_many                  :users, through: :roles
end

class Role < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :user
  belongs_to :website
end

So when I try to do: 因此,当我尝试执行以下操作时:

User.first.websites.create(name: "First")

I have this error 我有这个错误

ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

How can i create a new User Website in one line? 如何在一行中创建一个新的用户网站?

我认为,如果您从role模型中删除validates :name, presence: true ,那么它将起作用。

The validation error is actually coming from the Role model, which also has validation for the name attribute. 验证错误实际上来自角色模型,该模型也对name属性进行了验证。

You can do it in one line by creating the website through the role, using accepts_nested_attributes_for : 您可以使用角色通过accepts_nested_attributes_for创建网站,从而accepts_nested_attributes_for

class Role < ActiveRecord::Base
  validates :name, presence: true
  belongs_to :user
  belongs_to :website

  accepts_nested_attributes_for :website
end

User.first.roles.create(name: "Role name", website_attributes: { name: "Website name" })

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM