我正在创建一个小小的时事通讯应用程序,并且有双重选择加入限制'当我只是填写我的表单(订阅页面)并提交表单时,我会被重定向到我订阅的页面(这是正常的)但是我的表单会将查询字符串附加到我的表单的action属性(http:// localhost:3000 / newsletter / subscribe?format =)
路线:
match 'newsletter/subscription' => 'newsletter_subscriptions#subscription'
post 'newsletter/subscribe' => 'newsletter_subscriptions#subscribe'
控制器:
class NewsletterSubscriptionsController < ApplicationController
respond_to :html
# GET /newsletter/subscription
def subscription
respond_with (@subscription = NewsletterSubscription.new)
end
# POST /newsletter/subscribe
def subscribe
# If there's already an unconfirmed record with the submitted email, use that object otherwise create a new one based on the submitted email
sub_new = NewsletterSubscription.new
sub_new.email = params[:newsletter_subscription]['email']
sub_old = NewsletterSubscription.find_by_email_and_confirmed sub_new.email, 0
@subscription = sub_old || sub_new
if @subscription.save
Newsletter.delay.subscribed(@subscription) # with delayed_job
else
render :action => "subscription"
end
end
...
end
查看(newsletter_subscription / subscription.html.erb):
<h1>New newsletter_subscription</h1>
<%= form_for(@subscription, :url => newsletter_subscribe_path(@subscription)) do |f| %>
<% if @subscription.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@subscription.errors.count, "error") %> prohibited this newsletter_subscription from being
saved:</h2>
<ul>
<% @subscription.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email %>
<br/>
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
PS:如果有人可以评估我的红宝石代码,我会很高兴(上面发布),我仍然在学习很多,并希望看到一些指南&#39;或反馈,我想我还是可以学到很多东西。
答案 0 :(得分:3)
尝试删除您传递给@subscription
的{{1}}参数。由于路线中没有newsletter_subscribe_path
并且它是一个新对象,因此传递它并不合理。我假设这是被解释为格式的东西。
:id
至于您可以对代码进行的改进,我看到的最重要的事情是将旧/新订阅逻辑移动到模型中。
<%= form_for(@subscription, :url => newsletter_subscribe_path) do |f| %>
此处并不需要# in NewsletterSubscription
def self.with_email(email)
find_by_email_and_confirmed(email, 0) || new(:email => email)
end
# in controller
@subscription = NewsletterSubscription.with_email(params[:newsletter_subscription]['email'])
if @subscription.save
#...
和respond_to
,因为您只是处理HTML视图。你可以删除它。