标签: has-one-through

我该如何通过Association建立一个has_one?

对于一个has_one关联,我可以建立一个这样的关联:

foo.build_bar()
Run Code Online (Sandbox Code Playgroud)

我应该如何建立一个has_one, through:协会?

例如:

class Foo

  has_one :bar
  has_one :baz, through: :bar

end
Run Code Online (Sandbox Code Playgroud)

我应该如何建造baz?在这个例子中foo.build_baz得到一个No Method Error.

这里的文档说:

声明has_one关联时,声明类会自动获得与关联相关的四种方法:

association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
Run Code Online (Sandbox Code Playgroud)

然而,情况似乎并非如此.使用Pry来反省Foo我的实例我可以看到没有添加这样的方法,因为它将在has_one没有a 的情况下添加through:.

ruby-on-rails associations ruby-on-rails-3 has-one-through

6
推荐指数
1
解决办法
2517
查看次数

建立A有一个通过vs有很多通过未保存的模型

我写了一个宝石,允许Google Spreadsheets转换成Rails模型.此过程的顺序包括创建所有模型,然后连接它们的关联,然后保存所有模型.它支持所有可用的关联类型,并且在每种情况下都禁止一个,创建模型,建立关联,然后保存模型正常工作.例外情况如下:

我有一个简单的has_one, through关联(为简洁省略了属性访问):

class Left < ActiveRecord::Base
   has_many :middles, dependent: :destroy
   has_many :rights, through: :middles
end

class Right < ActiveRecord::Base 
   has_one :middle, dependent: :destroy
   has_one :left, through: :middle
end

class Middle < ActiveRecord::Base
  belongs_to :left
  belongs_to :right
end
Run Code Online (Sandbox Code Playgroud)

我发现一些不一致的行为取决于关联分配的哪一方:

从左到右分配:

left = Left.new
right = Right.new
left.rights << right
left.middles #[]
right.middle #nil
left.save!
left.middles # <Middle theme_id: 1, archive_resource_id: 1 >
Run Code Online (Sandbox Code Playgroud)

从左到右分配:

left = Left.new
right = Right.new
right.left = left
left.middles #[]
right.middle <Middle theme_id: …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails associations has-many-through ruby-on-rails-3 has-one-through

5
推荐指数
1
解决办法
603
查看次数

Laravel hasOneThrough 关系返回 null

我在MySQL数据库中有以下表结构:

Products
    id - integer
    name - string
    user_id -string

Users
    user_id - string
    password - string
    person_id - integer

Persons
    person_id - integer
    name - string
    email - integer
Run Code Online (Sandbox Code Playgroud)

我正在使用产品模型上的关系来获取有关通过谁链接的hasOneThrough详细信息。定义关系的代码如下:PersonUsers

public function product_user()
{
    return $this->hasOneThrough(
        'App\Person',
        'App\User',
        'person_id',
        'person_id',
        'user_id',
        'user_id'
     );
}
Run Code Online (Sandbox Code Playgroud)

但当我null尝试访问该属性时,它一直在product_user给我。null我无法更改数据库结构。在这种情况下如何定义正确的关系?

php orm laravel eloquent has-one-through

1
推荐指数
1
解决办法
1428
查看次数