我有一个模型条目,布尔列published
,默认设置为false
。下面是完整的迁移文件:模型布尔方法无法正常工作
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
在我models/entry.rb
我增加了以下方法:
def published?
Entry.where("published", true)
end
和index.html.erb
我有这样的:
<% @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 %>
但是,当我创建一个条目并导航到我的索引视图,条目显示为已发布。
您的'self.published?'方法一直返回true。 –
我明白了,我编辑了我的问题 - 我犯了一个错误,而不是'self.published?''我刚刚发布了''方法。我怎么能重写它? – AlexNikolaev94
它仍然一直返回'true'。在这个模型中不需要一个方法,下面的答案是正确的。 –