【问题标题】:Rails form not saving data with strong_params setRails 表单不保存设置了 strong_params 的数据
【发布时间】:2014-09-30 23:31:23
【问题描述】:

我的 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 %>

这里是作业控制器中的创建方法:

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

这里是作业控制器中的 job_params:

def job_params
  params.require(:job).permit(:box_count, :install_date)
  params.permit(:customer_id)
end

有谁知道为什么 :box_count 和 :install_date 不写入数据库?


从创建操作中添加了参数:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"i9w0nH16NG491Aa/pbG979VntnRjUGGlhvqIahJViEE=", "job"=>{"box_count"=>"5", "install_date"=>"101014"}, "commit"=>"Create Job", "customer_id"=>"1"}

【问题讨论】:

  • Ruby 方法将返回最后一行。所以它会返回params.permit(:customer_id)
  • @japed 即使将 :box_count 和 :install_date 移动到最后一行,它仍然不会写入数据库。
  • @DustinJames 向我们展示您的 params 来参加您的 create 行动

标签: ruby-on-rails database parameters controller


【解决方案1】:

我认为工作和客户之间存在关联。所以你做错了我的朋友。这样做:

Customer Modal

  has_many :jobs

Job Modal

  belongs_to :customer

比这样做:

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

这里是作业控制器中的 job_params:

def job_params
  params.require(:job).permit(:box_count, :install_date, :customer_id)      
end

希望这会有所帮助。谢谢

【讨论】:

  • 成功了!奇怪的是昨天我把 :customer_id 放在参数的第一行时遇到了麻烦,当我将它分开时它就起作用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 2020-11-08
相关资源
最近更新 更多