2012-07-31 83 views
0

從我以前的問題中知道我已經習慣了rails,目前我有一個create函數的問題,因爲它沒有保存數據庫中的組合框中的記錄,就像這樣的:保存在軌道上的記錄

enter image description here

,但它保存在數據庫中記錄的其餘部分,對檢查我鍵入:

rails console 
TankingLog.all 
TankingLog Load (0.7ms) SELECT "tanking_logs".* FROM "tanking_logs" 

[#<TankingLog id: 7, car_id: 28, cost: 3000.0, date: "2012-07-30 00:00:00", gallon: 2.0, gas_station_id: nil, km: 5000, created_at: "2012-07-30 22:00:40", updated_at: "2012-07-30 22:00:40">] 

正如你所看到的gas_station_id場是零,但它必須是選擇的電臺的ID 我讚賞黃昏時分的任何幫助,對不起,如果這是一個愚蠢的問題

這裏是形式:

<div class="container"> 
    <h2>new tanking log</h2> 
    <%= form_for ([@user,@car,@tankinglog]) do |f| %> 
     <div><%= f.label :cost %><br /> 
     <%= f.text_field :cost %></div> 

     <div><%= f.label :gallon %><br /> 
     <%= f.text_field :gallon %></div> 

     <div><%= f.label :km %><br /> 
     <%= f.text_field :km %></div> 

     <div><%= f.label :date %> <i>(format yyyy-mm-dd)</i> <br /> 
     <%= f.text_field :date %></div> 

     <div><%= f.label :Station %><br /> 
     <%= select("gas_station", "name", GasStation.all.collect {|gs| [ gs.name, gs.id ] }, { :include_blank => true })%></div> 
     <p> 
     if you don't see the station that you want, you can <%= link_to "create it", new_gas_station_path%> 
     </p> 

     <div><%= f.submit "create tanking",:class => "btn btn-primary" %></div> 
    <% end %> 
    <br /> 
    <%= link_to "Back", user_car_tanking_logs_path(@user, @car),:class => "btn btn-primary"%> 
    </div> 

和tankinglogcontroller

class TankingLogsController < ApplicationController 
def new 
@user = User.find(params[:user_id]) 
@car = @user.cars.find(params[:car_id]) 
@tankinglog = @car.tanking_logs.build 
end 

def create 
@user = User.find(params[:user_id]) 
@car = @user.cars.find(params[:car_id]) 
@tankinglog = @car.tanking_logs.build(params[:tanking_log]) 
if @tankinglog.save 
    redirect_to user_car_tanking_logs_path(@user, @car), :flash => { :notice => " new tanking created!" } 
else 
    redirect_to new_user_car_tanking_log_path ,:flash => { :notice => " sorry try again :(" } 
end 
end 
def index 
    @user = User.find(params[:user_id]) 
    @car = @user.cars.find(params[:car_id])  
    @tankinglog = @car.tanking_logs.all 
end 
end 

,如果你想看到的模型......

class TankingLog < ActiveRecord::Base 
belongs_to :gas_station 
belongs_to :car 
attr_accessible :car_id, :cost, :date, :gallon, :gas_station_id, :km 
validates_presence_of :cost, :date,:gallon,:km 
validates_numericality_of :cost, :gallon 
validates_numericality_of :km #:only_integer 
end 


class GasStation < ActiveRecord::Base 
has_many :tanking_logs 
attr_accessible :name 
validates_presence_of :name 
end 
+0

你能發表一些相關的代碼嗎? – Catfish 2012-07-31 15:03:07

+0

那麼請添加生成輸入字段的表單的代碼,以及實際保存數據的操作的代碼,以及更新操作的日誌 – 2012-07-31 15:03:52

回答

1

編輯此:

<%= f.select("gas_station_id", GasStation.all.collect {|gs| [ gs.name, gs.id ] }, { :include_blank => true })%></div> 
+0

謝謝! – Asantoya17 2012-07-31 15:22:48