在我看来无法调用我的关联表 [英] Can not call my associate table in my view
问题描述
在我看来无法调用我的关联表.试过这个.它是一个只添加到玩家的应用程序.按开始游戏"后,他应该会来到结果视图,那里是所有玩家的结果.那么我当然会有玩家"表的名称,然后是结果"表中的绑定结果.现在查询,我在后台输入bidningen,只要
Can not call my associate table in my view. have tried this. it is an application that only adds to the players. after the press "start game" and then he should come to the result view where the results of all players. then I will of course have the name of the "players" table and then the binding results from the "results" table. now in quire, I enter bidningen in the background as long as
查看:
<% @playersname.each do |p|%>
<ul>
<li><%= p.name %></li>
<li><%= p.results.try(:result) %></li>
</ul>
<%end%>
控制器:
class ResultsController < ApplicationController
def index
@playersname = Player.all
end
结束
型号:
class Result < ActiveRecord::Base
# attr_accessible :title, :body
has_many :players
end
迁移:
class CreateResults < ActiveRecord::Migration
def change
create_table :results do |t|
t.string "result", :limit => 40
t.string "cal", :limit => 40
t.string "sum",:limit => 300
t.timestamps
end
end
结束
推荐答案
CreateResults 迁移错过了 player_id 列.
The CreateResults migration miss the player_id column.
在 Result 类中执行 belongs_to :player
并更正迁移(或执行另一个迁移).
Do belongs_to :player
in your Result class and correct the migration (or do another one).
我不够清楚:我认为你颠倒了关系逻辑.你实际上做了一个结果有几个玩家".我想你希望一个玩家有几个结果?
I wasn't clear enough : I think you inverted the relationship logic. You actually did the "one result has several players". I suppose you want that a player has several results ?
class Player
has_many :results
end
class Result
belongs_to :player
end
所以你可以这样做:
@myplayer = Player.all.first
@myplayer.results #it is an array of player's results
@myplayerresult = @myplayer.results.first
puts @myplayerresult.result
如果您想要一对一的关系,请考虑将 has_many :results
替换为 has_one :result
,这样您就可以执行 @myplayer.result
得到你的结果.
If you want a one-to-one relationship, consider replacing has_many :results
by has_one :result
and so you can do @myplayer.result
to get your result.
这篇关于在我看来无法调用我的关联表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!