AlexNikolaev94
AlexNikolaev94

Reputation: 1209

Model boolean method doesn't work properly

I have a model Entry with boolean column published, which is set to false by default. Here's the complete migration file:

class CreateMultifloraEntries < ActiveRecord::Migration[5.0]
  def change
    create_table :multiflora_entries do |t|
      t.string :type, index: true
      t.string :title
      t.string :slug, unique: true
      t.json :payload
      t.integer :user_id, index: true
      t.boolean :published, default: false

      t.timestamps
    end
  end
end

In my models/entry.rb I added the following method:

def published?
  Entry.where("published", true)
end

and in index.html.erb I've got this:

<% @entries.each do |entry| %>
   # ...
   <% if entry.published? %>
     <p> Published <p>
   <% else %>
     <!-- There will be an AJAX request to set entry published later -->
     <%= link_to "Publish", "whatever-path" %>
   <% end %>
<% end %>

However, when I create an entry and navigate to my index view, the entry is shown as published.

Upvotes: 2

Views: 792

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Ok, for any boolean attribute, rails gives you a helper method by default. You don't need to define it. So, in your case entry.published? will work without your own written method. Remove your own method definition it is not needed.

Just to FYI one more thing is, you defined a class method, not an instance method. Like the method you wrote, is callable like Entry.published?, but not on the instance of Entry. But in this case entry.published? will work because Rails defined it for you out of the box, because publish is a boolean field. Now, you have to fix your class implementation of the method as:

def self.published?
  self.where(published: true).any?
end

Upvotes: 3

Related Questions