代码之家  ›  专栏  ›  技术社区  ›  Jack Smith

使用rails视图文件中的外键从不同的表中获取数据

  •  0
  • Jack Smith  · 技术社区  · 8 年前

    我在创造一个新的世界。html。erb文件,我试图列出所有球队及其对手。我有两个表:一个用户(团队)表和一个记录表。records表有两列(user_id,opporter_user_id)引用同一个users表。

    我的视图文件:

       <% @record.each do |record| %>
         <tr>
           <td><%= record.user.name %></td>          
           <td><%= record.opponent_user_id %></td>
        </tr>
       <% end %>
    

    而不是使用记录。user_id,我可以使用record将id替换为用户名。使用者名称然而,我不能对对手队做同样的事情。我试着用

        <td><%= record.opponent_user_id.user.name %></td>
    

    但那没用。如何用实际名称替换对手的用户id?

    其他信息如下

    控制器

      def prof
        @user = User.find(params[:id])
        @record = Record.where(user_id: @user.id)
      end
    

    表模式

      create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
        t.string "name"
        t.string "email"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.index ["email"], name: "index_users_on_email", unique: true
      end
    
      create_table "records", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
        t.bigint "user_id"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
        t.integer "opponent_user_id"
        t.index ["user_id"], name: "index_records_on_user_id"
      end
    

    谢谢你的帮助。我对rails还是新手。对于我不应该这样做的任何额外反馈,我也将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Anand    8 年前
    class Record < ActiveRecord::Base
      belongs_to :user, class_name: "User", foreign_key: "user_id"
      belongs_to :opponent_user, class_name: "User", foreign_key: "opponent_user_id"
    end
    

    在用户模型中:-

    class User < ActiveRecord::Base
      has_many :records, class_name: "Record", foreign_key: "user_id"
      has_many :opponent_user_records, class_name: "Record", foreign_key: "opponent_user_id"
    end
    

    作者:-

      def prof
        @user = User.find(params[:id])
        @records = @user.records
      end
    

       <% @records.each do |record| %>
         <tr>
           <td><%= record.user.name %></td>          
           <td><%= record.opponent_user.name %></td>
        </tr>
       <% end %>