如何创建另一个控制器操作来在 Rails 中创建对象?
我有一个名为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,你的代码看起来没问题,只是有一些事情。
你没有 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 okmap.resources :contact_emails, :member => {:skip => :post}
And everything should be just fine