0

I need the controller to check if a string exists in a table and then return "true" or "false" so that I can use it in an if statement. For example, if the string "Robert" exists in the "my_friends" table, I need to display those corresponding items related to "Robert" from another table called "goodtimes."

I realize the .exists won't work in this application because I'm searching for a string.

@my_friends.where(friend_id: 'Robert').exists?   #always returns false
    @goodtimes = goodtime.where friend_id: "Robert" #works

The pseudo code would look like this:

if (table x contains string "Robert")
    @goodtimes = goodtime.where friend_id: "Robert" #display goodtimes from table y

Thanks in advance, Dave

Dave G
  • 3
  • 2
  • You want to search that string in every column of the table? – Gerry May 07 '17 at 00:33
  • No, just the friend_id column. The friend_id column is in both tables. – Dave G May 07 '17 at 00:35
  • Use your model and do a regular AR query, what is the model of the table you want to query? – Gerry May 07 '17 at 00:37
  • I should have said that I'm new to Rails. I don't understand your question. The file in the model directory doesn't contain anything other than the class and then end. What's an AR query? Thanks btw for helping. – Dave G May 07 '17 at 00:42
  • AR stands fro ActiveRecord, and that's how rails (by default) queries the database. What have you assigned to `@my_friends`? You probably query the database using something like `MyFriends.where...`; with that you are using AR. – Gerry May 07 '17 at 00:49
  • I get a syntax error. dynamic constant assignment? – Dave G May 07 '17 at 00:53
  • 1
    Can you post the complete block of code your are using? – Gerry May 07 '17 at 00:54
  • OMG, it worked! Thank you so much. I've been working on this for days! I had your response typed incorrectly. – Dave G May 07 '17 at 00:55
  • Glad to help, but if you mean the answer below, that was not me, that's @shambalambala answer. If it worked you can thank him by accepting the answer :) – Gerry May 07 '17 at 01:00
  • Thank you both! This means so much to me. You are both good people! – Dave G May 07 '17 at 01:06

1 Answers1

0

You can check whether Robert exists or not by using .where().present

if @my_friends.where(:friend_id => 'Robert').present?
  # Robert exists
else
  # Robert doesn't exist
end

See this answer for more ways to check if a record exists.

Community
  • 1
  • 1
Aurélien Gasser
  • 3,043
  • 1
  • 20
  • 25