我对这一切都是新手,所以如果这听起来很疯狂,很抱歉!
我使用过这个教程:http://www.railsmine.net/2010/03/rails-3-action-mailer-example.html
我有一个新的联系方式,工作很好。
控制器位于app/ controller /support_CONTROLER.rb
class SupportsController < ApplicationController
def new
# id is required to deal with form
@support = Support.new(:id => 1)
end
def create
@support = Support.new(params[:support])
if @support.save
redirect_to('/', :notice => "Support was successfully sent.")
else
flash[:alert] = "You must fill all fields."
render 'new'
end
end
end和/app/ model /support.rb上的模型
class Support
include ActiveModel::Validations
validates_presence_of :email, :sender_name, :support_type, :content
# to deal with form, you must have an id attribute
attr_accessor :id, :email, :sender_name, :support_type, :content
def initialize(attributes = {})
attributes.each do |key, value|
self.send("#{key}=", value)
end
@attributes = attributes
end
def read_attribute_for_validation(key)
@attributes[key]
end
def to_key
end
def save
if self.valid?
Notifier.support_notification(self).deliver!
return true
end
return false
end
end但是,视图只能在views /support/new.html.rb (rendered views/support/_form.html.erb)中工作。
因此,我可以从localhost:3000/support/new调用Model / Controller,但是如果我尝试在根目录的另一个视图中呈现相同的表单,例如app/ view /contact.html.erb,我会得到:
undefined method `model_name' for NilClass:Class我认为这是因为它正在调用support目录之外的支持模型。
我必须在@support上创建一个实例才能调用它吗?如果是这样,那么最好的方法是什么?我想我快到了。我只希望联系人表单在多个页面上,而不仅仅是在suppport/new中
谢谢
查利
发布于 2011-11-07 22:58:48
是的,您需要在希望呈现表单的每个操作中创建一个@support变量。
另一种选择是重构表单以接受参数,这样您就更灵活了。例如,从您的视图:
<%= render :partial => "supports/form", :locals => {:support => @support} %>现在,您可以简单地引用support,因为它是一个local_assign,而不是在_form.html.erb中引用@support。
另一种选择是进一步重构表单,并担心在partial之外创建实际的form标记。
例如:
app/views/supports/new.html.erb
<%= form_for @support do |form| %>
<%= render :partial => "suppports/form", :object => form %>
<% end %>app/views/supports/_form.html.erb
<%= form.text_field :foo %>
<%= form.text_field :bar %>
...在这种情况下,当您使用object选项呈现partial时,您将在partial中获得一个与partial同名的局部变量。您在表单的路径上保持了更多的灵活性,但仍然可以呈现表单中的Support对象,同时保持应用程序之间的一致性。
为了说明这一点,您可以在其他地方使用它,方法如下:
app/views/foos/_create_foo_support.html.erb
<%= form_for @foo.support do |form| %>
<%= render :partial => "supports/form", :object => form %>
<% end %>发布于 2011-11-07 22:51:49
无论在哪里使用联系人表单,都必须传递@support对象。它在SupportsController#new中工作,因为您在那里初始化了变量。在您想要使用表单的所有其他地方,您必须执行相同的操作。
https://stackoverflow.com/questions/8037977
复制相似问题