简体   繁体   English

Rails:未定义的方法错误无法使用 attr_accessor 修复

[英]Rails: undefined method error not fixable with attr_accessor

I have created a very simple model called Discussion and one of the columns is a boolean called resolved.我创建了一个非常简单的 model,称为 Discussion ,其中一列是 boolean,称为已解决。 The idea being that once a discussion item has been resolved that value is set to true.这个想法是,一旦解决了讨论项目,该值就会设置为 true。

On the edit form, I tried to put in some logic based on the value of that field.在编辑表单上,我尝试根据该字段的值输入一些逻辑。

<%= form_for(@discussion) do |d| %>
    ...
<% if d.resolved == "true" %>
    <p>The discussion is resolved</p>
<% else %>
    <p>The discussion is not resolved</p>
<% end %>
<% end %>

However, I'm getting an error message但是,我收到一条错误消息

undefined method `resolved' for #<ActionView::Helpers::FormBuilder:0x00000101674678>

I tried adding an attr_accessor line to my model but that didn't do anything for me either.我尝试在我的 model 中添加 attr_accessor 行,但这对我也没有任何作用。 I'm not sure what I have to do to fix this.我不确定我必须做些什么来解决这个问题。 I'm pretty new to rails, so I'm sure that whatever the problem is it's probably pretty simple to fix, but I just don't get it.我对 Rails 很陌生,所以我确信无论问题是什么,解决起来都可能很简单,但我就是不明白。 Thanks.谢谢。

Because d represent an instance of the form builder, you want因为 d 代表表单构建器的一个实例,所以您想要

<% if @discussion.resolved %>

If resolved is represented as a "boolean" in ActiveRecord.如果解析在 ActiveRecord 中表示为“布尔值”。

every boolean column represents as predicate, so you can use:每个 boolean 列都表示为谓词,因此您可以使用:

if @discussion.resolved?
...
end

What you're looking for is the resolved?你要找的是解决了吗? method.方法。

<% if @discussion.resolved? %>

which is auto-generated for boolean columns.这是为 boolean 列自动生成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM