Ruby Syntax for finding same foreign key values in different tables

227 views Asked by At

I have a table (peas) containing several foreign keys in each row and listing them in it's index view. I have other tables (carrots) that contain the same foreign keys.

From the first table (peas) I want to find the row in the other table (carrots) that contain the same foreign key values, put that in a variable (@p) to be used inside a conditional statement to be displayed in the index view of the first table (peas). What I've created so far is not throwing an error so it's hard to diagnose.

I've tried to change the operand but having no success.

Pea Model (Adding method to Model because there are no database changes)

  def pea
    @p = Carrot.find({ :fk_id => 'pea.fk_id', :fk2_id => 'pea.fk2_id' })
  end

Corresponding Peas Index View (Inside an each loop)

<% if @p.present?  %>
 <p>Say This</p>
<% else %>
 <p>Say That</p>
<% end %>

Once I've found the row that matches the two foreign keys (fk_id & fk2_id) I'll know that the match is unique. In other words there will only be one row in Carrots that contains the same two foreign key values in Peas.

I feel like I'm missing something really obvious. I've searched similar questions and can't quite match this scenario enough to hack a solution together.

Pea belongs_to :Carrot
Carrot has_one :Pea

Any help in the right direction is appreciated.

RoR - Rails 4.2.5.2 / ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin14], Sqlite3 (dev), Postgresl (Prod), Mac

1

There are 1 answers

1
Nikita Misharin On

find only accepts primary_key as an argument. Use find_by for search by other attributes.

def pea
  @p = Carrot.find_by(fk_id: 'pea.fk_id', fk2_id: 'pea.fk2_id')
end

Also find throws an error if it find nothing, so if you see no errors chances are that you haven't called method pea at all.