我在初级网络应用程序上工作,使用简单的表格来保存用户的日期请求。
这是代码
视图/天/ index.html.erb
<%= form_for @daysoff, url: {action: "create"} do |f| %>
<%= f.date_field :offdate, id: 'altField' %>
<p> User holding the fort / Yerine bakicak kisi
<%= f.collection_select(:assign_id, @people, :id, :name) %> </p>
<%= f.hidden_field :user_id, value: @user.id %>
<%= f.submit "Submit" %>
<% end %>
控制器/ days_controller.rb
class DaysController < ApplicationController
unloadable
def index
@people = User.all
@user = User.current
@daysoff = Daysoff.new
# params[:daysoff][:user_id] = @user.id
end
def create
off_dates = params["daysoff"]["offdate"].try(:split,',')
off_dates.each do |off_date|
@days_off = Daysoff.new
@days_off.offdate = Date.strptime(off_date.strip, "%m/%d/%Y")
@days_off.user_id = User.current
@days_off.assign_id = params["assign_id"]
@days_off.status = 0
@days_off.save!
end
redirect_to "/days_off_redmine", :flash => { :success => "Istek gonderildi." }
end
没有任何模型验证。
数据库迁移文件。
class CreateDaysoffs < ActiveRecord::Migration
def change
create_table :daysoffs do |t|
t.date :offdate
t.integer :user_id
t.integer :assign_id
t.boolean :status
end
end
end
当我尝试填写并发布表格时, 正确填写了过期和状态,但user_id和assign_id将db插入为NULL。
+----+------------+---------+-----------+--------+
| id | offdate | user_id | assign_id | status |
+----+------------+---------+-----------+--------+
| 1 | 2015-07-14 | NULL | NULL | 0 |
| 2 | 2015-07-15 | NULL | NULL | 0 |
| 3 | 2015-07-14 | NULL | NULL | 0 |
| 4 | 2015-07-15 | NULL | NULL | 0 |
| 5 | 2015-07-22 | NULL | NULL | 0 |
| 6 | 2015-07-23 | NULL | NULL | 0 |
| 7 | 2015-07-21 | NULL | NULL | 0 |
| 8 | 2015-07-22 | NULL | NULL | 0 |
| 9 | 2015-07-21 | NULL | NULL | 0 |
| 10 | 2015-07-22 | NULL | NULL | 0 |
| 11 | 2015-07-21 | NULL | NULL | 0 |
| 12 | 2015-07-22 | NULL | NULL | 0 |
| 13 | 2015-07-29 | NULL | NULL | 0 |
| 14 | 2015-07-30 | NULL | NULL | 0 |
| 15 | 2015-07-29 | NULL | NULL | 0 |
| 16 | 2015-07-30 | NULL | NULL | 0 |
+----+------------+---------+-----------+--------+
为什么会出现这种情况?
答案 0 :(得分:0)
省略代码看起来很糟糕的事实......
表单属性出现在params[:daysoff]
中,您需要通过它来访问字段,例如:
通过params[:daysoff][:assign_id]
@days_off.user_id = User.current
应该是:@days_off.user_id = User.current.id
或@days_off应该在模型类中添加
belongs_to :user
并且它会正常工作,除非User.current是nil