2014-10-28 67 views
1

我遇到了质量分配和强参数的问题。在我的模型中,我有几个属性,这些属性是通过我的mysql数据库中的一列表示的。我也有一个领域,那不是。我只需要它来计算一个值。我不想将它存储在我的数据库中。Rails4没有数据库列的强参数

在我的控制,我定义的强参数:

def timeslots_params 
    params.require(:timeslot).permit(:employee_id, :dienstplan_id, :start_date, :start_time) 
    end 

但是当我试图访问START_TIME属性在我的控制,我发现了

undefined method `start_time' for #<Timeslot:0x007fff2d5d8070> error. 

定义的其他带有db列的参数存在并填充值。我是否错误理解强参数并且必须定义其他内容?

编辑:这里是代码,在那里我称之为timeslots_params:

def create 
    @e = Timeslot.new(timeslots_params) 
    @e.start_date = @e.start_date.to_s + " " + @e.start_time.to_s 

    if @e.save 
     current_user.timeslots << @e 
     respond_to do |format| 
     format.json { render :json => @e } 
     end 
    end 
    end 
+0

你可以发布'Timeslot'模型类的代码和你在那里定义'start_time'的地方吗? – Surya 2014-10-28 17:33:29

+0

发布您正在调用'timeslots_params'的行为并获取该错误。 – nikkon226 2014-10-28 18:24:28

+0

我已将代码添加到我的第一篇文章中 – user39063 2014-10-28 18:39:19

回答

1

请,只允许你希望你的用户数据发送PARAMS。如果START_TIME不是用户数据更新您的数据库,用这样的方式:

params.require(:timeslot).permit(:employee_id, :dienstplan_id, :start_date) 

强参数防止保存数据用户发送和你不希望他/她更新。

如果您使用:start_time,它必须在您的模型中定义。

行动,我看到您的更新:

@e.start_date = @e.start_date.to_s + " " + @e.start_time.to_s 

如果发送:START_TIME到一个时隙例如他们START_TIME必须时隙模型的方法。由rails定义,如果它是db字段,用attr_accesor或att_reader定义或由源模型上的def键定义。

如果不是@e.start_time触发器undefined method 'start_time'

再次编辑:

现在,start_time是一个模型变量。确保将它发送到表单的方式与字段相同。默认情况下,我们使用f <%= f.text_field :the_field %>。只是不要忘记f。

现在您必须再次允许此字段,如果您遵循我的第一条建议。

+0

实际上,它不一定要在模型中包含在参数中。 – nikkon226 2014-10-28 18:22:48

+0

现在,我已经在我的模型中定义了'attr_accessor:start_time'。现在我没有得到任何错误,但是start_time的值是零。我用pry检查过它。但是该值在POST请求中设置。 – user39063 2014-10-28 19:13:43

+0

你希望如何设置这个值?用户输入数据,使用Time.now,使用函数或...? – 2014-10-28 19:19:08

2

在你的模型提供访问start_time领域:

attr_accessor :start_time 

如果你只需要读访问:

attr_reader :start_time 
0

虽然Alireza的答案可以工作,但您也可以尝试定义符合setter点击你自己,然后你可以在保存前使用变量。

def start_time=(time) 

    # use variable time to do what you want with the model 

end