Yaofei Feng
Yaofei Feng

Reputation: 26

Ruby on Rails join two table

I have two tables and they looks like

listing1: PID:String Description:String 

listing2: Pid:String Category:String

I want to join these two table and display them in view

I tried to use the statement in my controller:

@tmp = Listing1.joins('LEFT OUTER JOIN listing2s ON listing1s.PID = listing2s.Pid')

@next = @tmp.where("listing2s.Category = 'toy'")

Now I have two problem:

  1. I can't access Listing2 attribute in my view. @tmp.Description is working but @tmp.Category failed and throw unknown method error

  2. In controller @next = @tmp.where("listing2s.Category = 'toy'") will not effect and I have to make it as @next = Listing1.joins('LEFT OUTER JOIN listing2s ON listing1s.PID = listing2s.Pid').where("listing2s.Category = 'toy'")

Any ideas?

Upvotes: 0

Views: 130

Answers (1)

troy
troy

Reputation: 2515

Yaofei,

First,"@tmp.Category failed" cause @tmp is an array,"@tmp.fisrt.Category" will be ok.

Second,the fail reason is the same as first,if you won't to write like that,you can use rails's scope,it really make the code clean and tidy.see:

scope :toy, -> { listing2s.Category = 'toy' }
scope :join_listing2_with_pid, -> { joins('LEFT OUTER JOIN listing2s ON listing1s.PID = listing2s.Pid') }

Finally,you can use scope like that:

@tmp = Listing1.join_listing2_with_pid
@next = Listing1.join_listing2_with_pid.toy

Upvotes: 1

Related Questions