开发者

Joining two tables in Rails but not on the primary key

开发者 https://www.devze.com 2023-03-10 01:30 出处:网络
I have been trying to do this for the last 12 hours and I can not figure this out. I have two tables: data:

I have been trying to do this for the last 12 hours and I can not figure this out.

I have two tables:

data:

data_id (primary key)

data text

userid int

users:

id (primary key)

name text

email text

I want to be able to pull the data so that I can have the user information, joined by data.userid with users.id

This is a really really simple SQL query, but it seems almost impossible in Rails.. Have I missed something fundamental here?

I am getting the error message: Mysql::Error: Unknown column 'users.data_id' in 'where clause': SELECT * FROM users WHERE (users.data_id = 2)

Can someone explain to me i开发者_StackOverflown a very simple way how to achieve this please?

Thanks


You need to follow the Rails conversions, for example the primary key is called 'id'. There are others so you might want to check of Rails Guides.

One thing which may trip you up in this specific example is pluralization, data/datum.

This should get you going:

TABLES

Datas:
  id:      integer (autoinc)
  data:    text
  user_id: integer (foreign key)

Users:
  id:      integer (autoinc)
  name:    varchar
  email:   varchar

By the way its best to create your tables using a migration, not manually.

MODELS

class Data < AR:Base
  belongs_to :user
end

class User < AR::Base
  has_many :datas
end

USEAGE

u = User.first
u.datas


What about:

@data = Data.find(params[:id])
@data.user.name

where you are clicking on data with id 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消