一段时间以来,我一直在努力解决这个问题。
所以在 rails 中我有一个带有 Action 索引的家庭 Controller ,看起来像这样
def index
@contact = Contact.new if !defined? @contact #automatically create a contact variable
end
在索引中,我使用 form_for (@contact) rails 辅助方法 - 它会自动调用 contacts_controller 的创建方法。我从 contacts_controller 重定向回家庭 Controller 的索引操作。这是我在 contacts_controller 中创建的内容,旨在澄清一些事情。
def create
@contact = Contact.new(params[:contact])
respond_to do |format|
if @contact.save
format.html { redirect_to :controller => 'home', :action =>"index", notice: 'Thanks for the Message!' } #
format.json { render json: @contact, status: :created, location: @contact }
else
format.html { redirect_to :controller => 'home', :action =>"index", notice: 'Errors Occurred', errors: @contact.errors.full_messages, anchor: "#contact"}
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
这是我的问题! 如何从 home/index 访问 @contact.errors ?具体来说,我需要单独访问错误 @contact.errors[:name]、@contact.errors[:email] 等。提前感谢您的帮助!!
最佳答案
通常它是在处理错误的地方使用渲染模板完成的。
def create
@contact = Contact.new(params[:contact])
respond_to do |format|
if @contact.save
format.html { redirect_to :controller => 'home', :action =>"index", notice: 'Thanks for the Message!' } #
format.json { render json: @contact, status: :created, location: @contact }
else
format.html { render :index } # Instead of redirecting, use render and in your template @contact.errors
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
赋值空变量的最佳实践是
@contact ||= Contact.new
关于ruby-on-rails - Rails Proper Syntax 用于访问不同 Controller 中模型的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26414216/