Bitwise
Bitwise

Reputation: 8461

Active Record Query - Rails

Currently I have a method called Visit and it basically adds on the the visit counter on Subscriber. This method gets triggered when a Subscriber enters their phone_number in a form. I simply want to make a active record query that will look something like this Susbcriber.find_by(params[id]).last.visit(this doesn't work BTW). Hopefully you get what I'm trying to do there, basically call the person that checked in last with their phone number. I'll show my code for clarity.

CONTROLLER METHOD:

 def search
  @subscriber = Subscriber.new
 end

 def visit
  @subscriber = Subscriber.find_by(params[:phone_number])
  if @subscriber
   @subscriber.visit ||= 0
   @subscriber.visit += 1
   @subscriber.save
   flash[:notice] = flash[:notice] = "Thank You #{@subscriber.first_name}. You have #{@subscriber.days_till_expired} until renewal"
  redirect_to subscribers_search_path(:subscriber)
 else
  render "search"
 end
end

There you can see the method that gets triggered when a Subscriber inputs their phone number. I simply want to call that person in the console.

CONTROLLER METHOD THAT IS NOT WORKING CURRENTLY:

  def create
    @subscriber = Subscriber.find(params[:subscriber_id])
    @comment = @subscriber.comments.build(comments_params)
  if @comment.save
    flash[:notice] = "Thank you!"
    redirect_to subscribers_search_path(:comments)
  else
    render "new"
  end
end

This is the method that needs the new query to find the Subscriber that just entered their phone number.

Let me know if you need more info? Thank You!

Upvotes: 0

Views: 59

Answers (1)

hightempo
hightempo

Reputation: 459

I'm editing my answer to be more inclusive based on the comments. It seems like you've got a number of issues going on here and maybe you need to step back and rebuild this step by step. Consider test driving it and/or at least verify that you're getting what you expect using a debugging tool as you go along (byebug, pry, or even just judicious use of 'puts' and 'inspect').

The find_by method requires that you specify the attribute that you're trying to use to find the row by, as well as the value of the attribute

@subscriber = Subscriber.find_by(phone_number: params[:phone_number])

If you are using the model's primary key, just use find:

@subscriber = Subscriber.find(params[:id])

If you're calling a controller action, params should always be present. Try inspecting the params before moving on with any of the rest of the code. Make sure that you're getting what you expect. If not, evaluate your view code.

Upvotes: 1

Related Questions