ruby-on-rails - Rails Proper Syntax 用于访问不同 Controller 中模型的错误

标签 ruby-on-rails ruby

一段时间以来,我一直在努力解决这个问题。

所以在 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/

相关文章:

ruby-on-rails - 如何删除单个 HABTM 关联项目而不删除该项目本身?

ruby-on-rails - 将 bool 参数传递给 rails Controller ?

ruby - Logstash:输出到Elasticsearch会导致Ruby出错,但可与stdout一起使用

ruby-on-rails - 已安装 Rails 但 rails 命令显示未安装

ruby-on-rails - Rails Assets 管道中的动态 CSS,即时编译

ruby - 如何在 ruby​​ 中使用 getoptlong 类?

ruby-on-rails - rake 路由错误 "Missing :action key on routes definition"

javascript - Rails jquery 按动态值选择

ruby-on-rails - Rails - 特殊验证案例

ruby-on-rails - 如何在 ruby​​ on rails 中创建向导表单