从 Rails 中的关系数据库中提取信息
我正在尝试从专辑数据库中提取艺术家的姓名。 这是我的两个模型
class Album < ActiveRecord::Base
belongs_to :artist
validates_presence_of :title
validates_length_of :title, :minimum => 5
end
class Artist < ActiveRecord::Base
has_many :albums
end
,这是专辑控制器
def index
@ albums = Album.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @albums }
end
end
和索引视图:
<% @albums.each do |album| %>
<tr>
<td><%=h album.id %></td>
<td><%=h album.title %></td>
<td><%=h album.artist.name %></td>
</tr
<% end %>
我的最终结果 html 对于艺术家领域来说是这样的!
#<Artist:0x000001022e4868>
如果我将其设置为artist.name
我明白了:
undefined method `name' for nil:NilClass
我做错了什么?
I am trying to pull the name of the Artist from the Albums database.
These are my two models
class Album < ActiveRecord::Base
belongs_to :artist
validates_presence_of :title
validates_length_of :title, :minimum => 5
end
class Artist < ActiveRecord::Base
has_many :albums
end
And here is the Albums Controller
def index
@ albums = Album.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @albums }
end
end
And the View from the index:
<% @albums.each do |album| %>
<tr>
<td><%=h album.id %></td>
<td><%=h album.title %></td>
<td><%=h album.artist.name %></td>
</tr
<% end %>
My end result html is coming out like this for the artist field!
#<Artist:0x000001022e4868>
and if I set it to artist.name
I get this:
undefined method `name' for nil:NilClass
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的艺术家与专辑的关系正在发生一些变化。如果您收到该错误,您将得到一个零艺术家,这意味着密钥没有保存在表中。手动检查你的表并确保关系存在,如果不存在那么你就找错了地方,你应该修复你的保存。
Something is going on the saving of your artists->album relationship. If you're getting that error you're getting a nil artist back which means the key isn't being saved in the table. Check your table manually and make sure the relation is there if it's not then you're looking in the wrong place, you should be fixing your save.
您需要做类似的事情:
可以这么说,您使用它的方式正在显示整个对象。
You need to do something like:
The way you used it you are displaying whole object, so to speak.
听起来好像您有一个没有艺术家的专辑(artist_id 为空或设置为不再存在的artist_id)。
您可以尝试:
Sounds like you have an Album without an Artist (either artist_id is null or set to an artist_id that no longer exist).
You can try:
前面列举的内容的另一种编写方式。
我建议进入脚本/控制台并手动逐步完成提取所有文章的过程,然后打印出所有艺术家姓名。
顺便说一句,如果您在生产中运行此代码,您可能应该使用预加载,
这会更有效。
Another way to write what was enumerated earlier.
I would recommend going into script/console and manually stepping through the process of pulling all your articles and then printing out all the artist names.
BTW, if you're running this code in production you should probably use eager loading
This will be much more efficient.
您的数据库表中是否确实正确设置了数据?如果您的艺术家和专辑模型保存正确,那么它应该看起来像这样:
Do you actually have data correctly set up in your database tables? If your Artist and Album models are being saved correctly then it should look something like this: