datepicker不保存日期

时间:2012-05-19 17:37:36

标签: ruby-on-rails datepicker has-many-through

我在表WritingUser之间有一个联接表Exercise。我的模特是

class Writing < ActiveRecord::Base
    belongs_to :user
    belongs_to :exercise
    attr_accessible :writing_date, :exercise_id
end

我按照Guide了解了has_many:通过关联

我的桌子出生在

class CreateWritings < ActiveRecord::Migration
  def self.up
    create_table :writings do |t|
      t.integer :user_id
      t.integer :exercise_id
      t.date :writing_date
      t.timestamps
    end
  end
  def self.down
    drop_table :writings
  end
end

我的writings_controller是:

 # encoding: utf-8
 class WritingsController < ApplicationController
    def create
        @writing = current_user.writings.build(:exercise_id => params[:exercise_id], :writing_date => params[:writing_date])
       if @writing.save
            flash[:notice] = "added writing."
            redirect_to root_url
       else
            flash[:error] = "not added."
            redirect_to root_url
       end
    end
    def new
       @writing = current_user.writings.new
       @exercise = Exercise.all
       respond_to do |format|
          format.html # new.html.erb
          format.xml  { render :xml => @writing }
       end
    end
end

和我的_form.html.erb就像

 <%= form_for(@writing) do |f| %>
  <div class="field">
   <%= f.text_field :writing_date %>
  </div>
  <div class="actions">
    <%= f.submit "add a writing", :class => "awesome custom red" %>
  </div>
 <% end %>

问题?数据未从writing_date保存到数据库。我正在使用jQuery和datepicker。 我按照日志

Started POST "/writings" for 127.0.0.1 at 2012-05-19 19:55:23 +0300
  Processing by WritingsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"q3xXMxVd9PsI346ph9CILLm8x74uCFokz3/2yOA0CeI=", "exercise_id"=>"7", "writing"=>{"writing_date"=>"2012-05-19"}, "commit"=>"add a writing"}

一切都好但是......

AREL (0.3ms)  INSERT INTO "writings" ("user_id", "exercise_id", "writing_date", "created_at", "updated_at") VALUES (1, 7, NULL, '2012-05-19 16:55:23.719410', '2012-05-19 16:55:23.719410')

writing_date为空。

2 个答案:

答案 0 :(得分:2)

我认为您需要将datepicker配置为其他格式。例如:

$(".datepicker").datepicker({
            dateFormat : "dd MM yy"
});

可以在此处找到Ruby日期格式:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html 以及相关问题:Rails 3.1 text_field form helper and jQuery datepicker date format

答案 1 :(得分:0)

根据您的参数,"writing"=>{"writing_date"=>"2012-05-19"}"writing_date"位于"writing"哈希值下,但您只传递params[:writing_data]参数;这就是为什么它不起作用。

@writing = current_user.writings.build(:exercise_id => params[:exercise_id], :writing_date => params[:writing_date])
  

而不是params [:writing_date]你应该使用   PARAMS [:写入] [:writing_date]

所以你必须通过以下方式改变它:

@writing = current_user.writings.build(:exercise_id => params[:exercise_id], :writing_date => params[:writing][:writing_date])