[英]Rails form not saving data with strong_params set
I have the following form in my rails test_app: 我的rails test_app中具有以下形式:
<%= form_for([@customer, @job]) do |f| %>
<% if @job.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@job.errors.count, "error") %> prohibited this job from being saved:</h2>
<ul>
<% @job.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :box_count %><br>
<%= f.number_field :box_count %>
</div>
<div class="field">
<%= f.label :install_date %><br>
<%= f.text_field :install_date %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Here is the create method in the jobs controller: 这是作业控制器中的create方法:
def create
@job = Job.new(job_params)
@customer = Customer.find(params[:customer_id])
respond_to do |format|
if @job.save
format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
format.json { render action: 'show', status: :created, location: @job }
else
format.html { render action: 'new' }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
And here are the job_params in the jobs controller: 这是jobs控制器中的job_params:
def job_params
params.require(:job).permit(:box_count, :install_date)
params.permit(:customer_id)
end
Does anyone know why :box_count and :install_date do not write to the DB? 有谁知道为什么:box_count和:install_date不写入数据库?
Added params from the create action: 从create动作添加了参数:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"i9w0nH16NG491Aa/pbG979VntnRjUGGlhvqIahJViEE=", "job"=>{"box_count"=>"5", "install_date"=>"101014"}, "commit"=>"Create Job", "customer_id"=>"1"}
I think there is an association between Job & Customer. 我认为工作与客户之间存在关联。 So you are doing it wrong my friend.
所以你做错了我的朋友。 Do this in this way:
以这种方式执行此操作:
Customer Modal
has_many :jobs
Job Modal
belongs_to :customer
Than do this: 比这样做:
def create
@customer = Customer.find(params[:customer_id])
@job = @customer.jobs.build(job_params)
respond_to do |format|
if @job.save
format.html { redirect_to customer_path(@customer), notice: 'Job was successfully created.' }
format.json { render action: 'show', status: :created, location: @job }
else
format.html { render action: 'new' }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
And here are the job_params in the jobs controller: 这是jobs控制器中的job_params:
def job_params
params.require(:job).permit(:box_count, :install_date, :customer_id)
end
Hope this will help.Thanks 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.