在视图中使用来自模型 类 的自制变量?

Using self made variables from model classes in views?

您好,我是 rails 上 ruby 的新手,到目前为止我已经完成了 this tutorial。我现在正在尝试添加功能,以便我可以在评论发布时通过电子邮件向某人发送评论,我正在努力。

我似乎无法开始工作的唯一部分是让我的视图识别我在评论中设置的变量 class(在 bd 中)。

在下面显示的代码中,我试图检查是否输入了电子邮件地址。如果是,则尝试发送;如果不是,它会像往常一样发布评论。我已经设置了一个布尔值来确定是否输入了电子邮件。但是后来在 _comment.html.erb 我无法访问它。这是为什么?

comment.html.erb

  <p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>
<p>
<%= comment.attempted.to_str %> <==== this line crashes as attempted is a nil class
</p>

<% if(comment.attempted == true) %>
    <p>
    your email was sent
    </p>
  <% end %>



<p>
  <%= link_to 'Destroy Comment', [comment.article, comment],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>
</p>

_form.html.erb(这是建立初始评论的原因)

   <p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
</p>

<p>
  <strong>Comment:</strong>
  <%= comment.body %>
</p>
<p>
<%= comment.body.to_str %>
</p>

<% if(comment.attempted == true) %>
    <p>
    your email was sent
    </p>
  <% end %>



<p>
  <%= link_to 'Destroy Comment', [comment.article, comment],
               method: :delete,
               data: { confirm: 'Are you sure?' } %>
</p>

comments_controller.rb

    class CommentsController < ApplicationController
http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy

  def create
    @article = Article.find(params[:article_id])
    @comment = @article.comments.create(comment_params)
    @comment.attempted = false


    if(!@comment.email.empty?)
    @comment.attempted = true
    if(@comment.email.include? '@')
    UserMailer.comment_email(@comment.email,@comment.body).deliver_now
    end
    end
    redirect_to article_path(@article)
  end

对于 _comment.html.erb 中的说明,我可以访问 comment.boby 和 comment.commenter 就好了,但尝试为零。为什么会这样,我该如何解决?

这里最明显的问题是您没有保存对评论所做的更改。

当需要迭代记录的评论时,该模型是从数据库重新生成的,它是一个单独的实例。

最有可能的解决方法是:

# Prepare but do not save a new model
@comment = @article.comments.build(comment_params)
@comment.attempted = false

# ... Stuff that may alter @comment.attempted

# Save the new instance.
@comment.save!

看起来你的方法中有一个循环:

定义创建 @article = Article.find(参数[:article_id]) @comment = @article.comments.create(comment_params)

这将再次调用创建函数。 也就是说,您的代码永远不会到达下一行的作业:

@comment.attempted = 假

这就是 comment.attempted 在视图中解析 'nil' 的原因,因为它从未在控制器中设置。

我会这样重写:

def create
  @article = Article.find(params[:article_id])
  @comment.attempted = false

  if(!@comment.email.empty?)
    @comment.attempted = true
    if(@comment.email.include? '@')
      UserMailer.comment_email(@comment.email,@comment.body).deliver_now
    end
  end

  # This line adds the comment instance to the article's comments collection.
  @article.comments << @comment

  redirect_to article_path(@article)
end