如何创建另一个控制器操作来在 Rails 中创建对象?

发布于 2024-09-01 21:02:08 字数 640 浏览 1 评论 0原文

我有一个名为 Contact_Email 的模型。当电子邮件模板通过 ActionMailer 发送到特定联系人时,作为创建操作的一部分,它会在 .save 时发送该模板。

但是,我想创建一个“跳过”操作,它也会创建 Contact_Email,但不发送 ActionMailer 并允许我以不同的方式设置状态。

我想创建一个单独的操作,因为我想让它响应一个remote_for_tag,这样我就可以有一个ajax按钮指示它已被“跳过”:

这是我尝试过的,但是当它创建一个Contact_Email时,我最终得到当我想返回并再次查看所有联系人时出现错误。

  def skip
    @contact_email = ContactEmail.new
    @contact_email.contact_id = params[:contact_id]
    @contact_email.email_id = params[:email_id]

    @contact_email.status = "skipped"

    if @contact_email.save
      flash[:notice] = "skipped email"
      redirect_to contact_emails_url
    end
  end

I have a model called Contact_Email. When an Email template is sent through ActionMailer to a specific Contact, as part of the Create action it sends it through upon .save.

However, I want to create a "skip" action which also creates a Contact_Email, but does NOT send an ActionMailer and allows me to set the status differently.

I want to create a separate action because I want to make this respond to a remote_for_tag so that I can just have an ajax button indicate it has been "skipped":

Here's what I tried, but while it creates a Contact_Email, I end up getting an error when I want to go back and view all the Contacts again.

  def skip
    @contact_email = ContactEmail.new
    @contact_email.contact_id = params[:contact_id]
    @contact_email.email_id = params[:email_id]

    @contact_email.status = "skipped"

    if @contact_email.save
      flash[:notice] = "skipped email"
      redirect_to contact_emails_url
    end
  end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪是无色的血 2024-09-08 21:02:08

嗯,你的代码看起来没问题,只是有一些事情。

  • 你没有 else 语句,如果你的
    @contact_email 没有保存?

  • 您绝对不应该单独分配所有参数。在 contact_email 视图中使用表单并
    控制器中的@contact_email = ContactEmail.new(params[:contact_email])。尽管单独“跳过”分配是可以的

    ,但

  • 正确定义您的路线。在这种情况下
    map.resources :contact_emails, :member => {:跳过=> :帖子}
    一切都应该很好

Well, your code seems ok, just a few things.

  • You have no else statement, what if your
    @contact_email is not saved?

  • You should definately NOT assign all of the params separately. Use a form in the view for contact_email and
    @contact_email = ContactEmail.new(params[:contact_email]) in controller. Though having "skipped" assigned separately is ok

  • Define you routes correctly. In this case
    map.resources :contact_emails, :member => {:skip => :post}
    And everything should be just fine
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文