Reddirt
Reddirt

Reputation: 5953

Rails scope test in view

I have a scope in worequests model:

scope :notcompl, where("statuscode_id != ?", Statuscode.last.id)

I would like to only show the edit button in the worequests show page if the worequest is notcompl. I tried this and got undefined method:

<% if @worequest.notcompl? %>
  <= link_to 'Edit', edit_worequest_path(@worequest), :class => 'btn btn-success' %>
<% end %>

What is the correct syntax?

Thanks for the help!

Upvotes: 0

Views: 325

Answers (3)

cortex
cortex

Reputation: 5206

From doc:

Scope: Adds a class method for retrieving and querying objects.

The problem is that you are calling the notcompl method in an instance not in the class. Worequest.notcompl should work (not in the same example).

PS: See @alexBrand answer.

Upvotes: 0

AlexBrand
AlexBrand

Reputation: 12399

A scope will find all the records that satisfy your condition.

It looks like what you want to do is check if the worequest has a statuscode_id of Statuscode.last.id. What you need is an instance method on your class instead of a scope:

 class Worequest < ActiveRecord::Base

    def not_complete?
        statuscode != Statuscode.last.id
    end
 end

Then in your view, you can check if the Worequest is complete or not:

<% if @worequest.not_complete? %>
  <= link_to 'Edit', edit_worequest_path(@worequest), :class => 'btn btn-success' %>
<% end %>

Also, defining a scope creates a method with the same name as the scope. So, calling .notcompl is not the same method as calling .notcompl? - which explains the undefined method issue you ran into.

Upvotes: 1

Jim Stewart
Jim Stewart

Reputation: 17323

Scopes belong in models, not in controllers. Move it to Worequest and it should work.

Upvotes: 0

Related Questions