如何在铁轨中建立一个双向联合街道

时间:2016-07-19 19:42:46

标签: ruby-on-rails-4

我有两个表,usersprofilesusers has_one profileprofiles belongs_to user

我可以@profiles.user.email访问users表中的email列。但是,我无法@users.profile.lastname访问lastname表中的profile列。它似乎只有一条街而且向上。

我怎样才能走这条双向街道并向下走?

2 个答案:

答案 0 :(得分:0)

has_one-belongs_to关系已经是双向的。

确保您拥有:

用户模型

List<Person> a = new List<Person> {
  new Person {
    Id = 1    
  }
};

List<Person> b = new List<Person> {
  new Person {
    Id = 1    
  }
};

var r = a.SequenceEqual(b);

个人资料模型

class User < ApplicationRecord
   has_one :profile
end

如果您正确设置了这两个设置,那么请在答案中添加一些代码,以便人们可以查看问题所在。

<强>更新

您可以使用rails控制台测试关联是否正常工作。在终端中使用class Profile < ApplicationRecord belongs_to :user end 以沙盒模式打开rails控制台(完成后将回滚所有更改)。

在控制台中创建一个用户和一个配置文件,然后检查它是否有效。

rails c -s

然后尝试user = User.create!(email: 'example@email.com') user.create_profile!(last_name: 'test') ,看看你得到了什么!

答案 1 :(得分:0)

我创建了一个全新的应用程序来测试关联。是的,他们是两条路。

当我在配置文件表中将主键更改为user_id时,必定会出错...

对不起,我过早地提出了这个问题。