0

新来这里的rails。我的关联设置如下,它可能不是理想的方式,因此非常欢迎任何建议:

User has many posts (posts table has user_id)
User has one profile (profile table has user_id)

在我的帖子控制器视图中,我想显示属于拥有帖子的用户的个人资料的名称 (profile.name)。

我天真的第一个猜测是,<%= @post.user.profile.name %>但这显然行不通。

这是我的模型中定义的关联:

class User < ActiveRecord::Base
  has_many :posts
  has_one :profile
end

class Post < ActiveRecord::Base
  belongs_to :user
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

这是视图中的代码: <%= @post.user.profile.name %>

错误是未定义的方法配置文件

4

2 回答 2

0

您必须在模型 user.rb 中提及以下内容

has_many :posts
has_one :profile

配置文件.rb

belongs_to :user

post.rb

belongs_to :user

然后<%= @post.user.profile.name %>应该工作。

如果您的数据仍然存在问题

于 2012-09-27T06:17:23.207 回答
0

您需要在和模型中定义belongs_to关系才能完成这项工作。例如:postsprofile

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

profile对模型做同样的事情

于 2012-09-27T06:22:49.840 回答