0

正如您从我之前的问题中知道的那样,我已经习惯了 rails,目前我的 create 函数有问题,因为它没有保存数据库中组合框中的记录,如下所示:

在此处输入图像描述

但它将其余记录保存在数据库中,为了检查它我输入:

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 字段为 nil,但它必须是所选车站的 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>

和 tankinglog 控制器

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
4

1 回答 1

1

编辑这个:

<%= f.select("gas_station_id", GasStation.all.collect {|gs| [ gs.name, gs.id ] }, { :include_blank => true })%></div>
于 2012-07-31T15:19:28.317 回答