未定义的方法`title'为零:红宝石中的NilClass

时间:2016-05-09 06:06:26

标签: ruby-on-rails ruby ruby-on-rails-3

当我渲染页面时,我得到undefined method 'title' for nil:NilClass这是我的代码:

的routes.rb

get 'contact-us' => "pages#contact_form"
post 'contact-us' => "pages#contact_us"

pages_controller.rb

#http://localhost:3000/contact-us
def contact_form 
    @page = Page.find_by_seo('contact-us')
    @inquiry = Inquiry.new
  end

  def contact_us
    @inquiry = Inquiry.new(inquiry_params)
    respond_to do |format|
      if @inquiry.save
        InquiryMailer.welcome_email(@inquiry).deliver
        format.html { redirect_to :back, success: 'Your request successfully sent.' }
        format.json { render '/contact-us', status: :created, location: @inquiry }
      else
        format.html { render :contact_form, notice: 'Please fill all the fields.' }
        format.json { render json: @inquiry.errors, status: :unprocessable_entity }
      end
    end
  end

contact_form.html.erb

<div class="contact_left">
    <ul class="contact-form_address">
      <li><%= @page.title %></li>
      <li><%= @page.description.html_safe %></li>
    </ul>
    <div class="map">
      <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d119743.53374944824!2d85.75041271337584!3d20.300870219682118!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3a1909d2d5170aa5%3A0xfc580e2b68b33fa8!2sBhubaneswar%2C+Odisha!5e0!3m2!1sen!2sin!4v1460021407530" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
     </div>
</div>
<div class="contact_right">
   #Contact Form here...
</div

请告诉我如何获得@page.title零值?并给我解决方案。

2 个答案:

答案 0 :(得分:2)

根据您的评论,我猜您必须为修复添加此内容

def contact_us
  respond_to do |format|
    if 
     .....
    else
     @page = Page.find_by_seo('contact-us')
     ....
     ....
    end
  end
end

检查差异b / w renderre-direct

答案 1 :(得分:1)

试试这个 -

def contact_us
    contact_form
    @inquiry = Inquiry.new(inquiry_params)
    respond_to do |format|
      ...
      ...
    end
  end