模型数据未显示在#show rails中

时间:2018-02-16 01:30:38

标签: ruby-on-rails

我正在努力创建一个网站,人们可以上传他们的财产。我创造了一个新的模型和控制器,人们可以在这里做到这一点。数据已成功保存到数据库中,但不会在显示页面上显示。所有字段都返回空白。

Started POST "/investments" for 127.0.0.1 at 2018-02-16 11:17:37 +1000
(6.7ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" 
ORDER BY "schema_migrations"."version" ASC
Processing by InvestmentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"r2WOptmoB7Icoal2SHVBTjyhiaLBKoBMydxIyLbiOr6lTs6UVvs0fvuj3TS2whDpLYouGYkWzP1AEg/GghbJAQ==", "investment"=>{"title"=>"test", "description"=>"test", "propertytype"=>"test", "bedrooms"=>"test", "carpark"=>"test", "landsize"=>"test", "equity"=>"test", "cashflow"=>"test", "rating"=>"test"}, "commit"=>"Save Investment"}

show.html.erb

  <strong>Title:</strong>
  <%= @investment.title %>
  <%= @investment.excerpt %>
  <%= @investment.description %>
  <%= @investment.propertytype %>
  <%= @investment.bedrooms %>
  <%= @investment.carpark %>
  <%= @investment.landsize %>
  <%= @investment.equity %>
  <%= @investment.cashflow %>
  <%= @investment.rating %>

investments_controller.erb

class InvestmentsController < ApplicationController

    def show
    @investment = Investment.new(params.permit(:title, :excerpt, :description, :propertytype, :bedrooms, :carpark, :landsize, :equity, :cashflow, :rating))
    end

    def new
    end

    def create
        @investment = Investment.new

        @investment.save
        redirect_to @investment
    end


private
  def investment_params
    params.permit(:title, :excerpt, :description, :propertytype, :bedrooms, :carpark, :landsize, :equity, :cashflow, :rating)
  end
end

的routes.rb

 Rails.application.routes.draw do
  mount Ckeditor::Engine => '/ckeditor'
    get 'pages/index' => 'high_voltage/pages#show', id: 'index'
    root :to => 'high_voltage/pages#show', id: 'index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  resources :investments
end

这里是最终结果^

2 个答案:

答案 0 :(得分:2)

您应该通过其ID找到Investment对象。目前,您正在尝试在Show上实例化一个新对象。例如:

@investment = Investment.find(params[:id])

而不是

@investment = Investment.new(params.permit(:title, :excerpt, :description, :propertytype, :bedrooms, :carpark, :landsize, :equity, :cashflow, :rating))

此外,您的create方法正在保存一个空白的投资对象,应将其更改为以下内容:

@investment = Investment.new(investment_params)

答案 1 :(得分:1)

您确定投资已保存吗?除了安东尼正确陈述的变化之外:

  

@investment = Investment.find(params [:id])#在show。

     

@investment = Investment.new(investment_params)#in create

您必须更改方法 investment_params

def investment_params
  params.require(:investment).permit(:title, :excerpt, :description, :propertytype, :bedrooms, :carpark, :landsize, :equity, :cashflow, :rating)
end