【发布时间】:2016-05-08 14:53:26
【问题描述】:
如图所示的 has_many 连接数据库
class Address < ActiveRecord::Base
has_many :years, dependent: :destroy
has_many :people, through: :years
end
class Year < ActiveRecord::Base
belongs_to :address
belongs_to :person
end
class Person < ActiveRecord::Base
has_many :years, dependent: :destroy
has_many :addresses, through: :years
end
我在使用 Years 的列表视图时遇到问题,即 Views>Years>list.html.erb
以下是不起作用的示例:
# table headers here
<% @years.each do |y| %>
<tr>
<td><%= y.year_date %></td>
<td><%= y.person_id %></td>
<td><%= y.person.given_name %></td>
<td><%= y.person.last_name %></td>
...
<% end %>
year_date 是地址上的人的日期,如果given_name 和last_name 行不存在,则显示正常。
year.person_id 也显示得很好。
但是year.person.given_name 和year.person.last_name 不显示。 given_name 和 last_name 是 Person 表中的一个字段。
错误是undefined method given_name for nil:NilClass。
显然有点菜鸟,否则这会更明显。部分问题可能在于如何对搜索进行措辞。
完整代码在这里:https://bitbucket.org/MtnBiker/crores5
感谢您的建议。找了好几天了。
编辑:环顾四周开始想知道外键,这是我通过 pgAdmin 在数据库中找到的。
ALTER TABLE people
ADD CONSTRAINT fk_rails_56c79562d9 FOREIGN KEY (address_id)
REFERENCES addresses (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION;
编辑 2. 添加控制器:
class YearsController < ApplicationController
helper_method :sort_column, :sort_direction
before_action :set_year, only: [:show, :edit, :update, :destroy]
def index
@years = Year.all
@years = Year.order(sort_column + " " + sort_direction)
end
架构?
CREATE TABLE years
(
id serial NOT NULL,
year_date date,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
resto boolean,
resid boolean,
source text,
person_id integer,
address_id integer,
title character varying,
CONSTRAINT years_pkey PRIMARY KEY (id),
CONSTRAINT fk_rails_8fc1813509 FOREIGN KEY (person_id)
REFERENCES people (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fk_rails_e1624dbb3f FOREIGN KEY (address_id)
REFERENCES addresses (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE years
OWNER TO gscar;
-- Index: index_years_on_address_id
-- DROP INDEX index_years_on_address_id;
CREATE INDEX index_years_on_address_id
ON years
USING btree
(address_id);
-- Index: index_years_on_person_id
-- DROP INDEX index_years_on_person_id;
CREATE INDEX index_years_on_person_id
ON years
USING btree
(person_id);
编辑:在这个冗长(抱歉)的讨论结束时给出答案。
【问题讨论】:
-
请在您的问题中包含您的相关架构和控制器。
-
我写了一篇文章,但没有真正的解决方案;如有必要,我会删除,但更重要的是,如果我们跳进聊天以对其进行排序会更好。如果您发表评论,我们可以修复它
-
也可能是插值问题
-
丰富。这边没聊过,不知道怎么实现。私人或有渠道。看起来像8小时的时间差异。因此可能是明天早上我的时间。 -8 格林威治标准时间
标签: ruby-on-rails postgresql foreign-keys jointable