简体   繁体   English

通过哈希或数组更新

[英]update via Hash or Array

I want to update the subject_id field in Period Model .Where the period loop will be inside the Form. 我想更新期间模型中subject_id字段,其中期间循环将在表单内。 SO, when I submit the Form the passing Parameter is coming as an hash, where Key is the Period.id and the Value is subject_id . 因此,当我提交表单时,传递的参数作为哈希表传入,其中Key是Period.id ,而Value是subject_id So, How can I update it. 因此,如何更新它。

In my Show.html.erb I has 在我的Show.html.erb中,

 <%= form_tag update_institutes_path, method: : put do %> <% @period.each do |cc | %> <%= cc.subject.name %> <%= collection_select('id', cc.id, Subject.all, : id, : name, selected: cc.id, prompt: true) %> <% end %> <%= submit_tag %> <% end %> 

The SHow action I has show动作我有

 def show @period = Period.all end 

In the Update action I have 更新操作中,我有

 def update @period = params[:id] keys, values = @period.map { |k,v| [k.to_i, v.to_i] }.transpose values.each { |f| Period.all.update_all(:subject_id => f) } end 

where @period = params[:id] give a parameter like @period = params[:id]给出类似的参数

  #Parameters: {"utf8"=>"✓", "authenticity_token"=>"8SNaUIQ6ZwjYOqBX07QYyVJsbuvYTL2TotSqIg0yj98nYXq5XqJ5XRHqlCvl1aw0lLg9vowyDOl3Hhm+hYDaOA==", "id"=>{"1"=>"3", "4"=>"2"}, "commit"=>"Save changes"}
  1. where 1 and 4 in the hash is period_id 哈希中的1和4是period_id
  2. 3 and 2 in the hash is subject_id. 哈希中的3和2是subject_id。

Then I converted the hash to keys and values 然后我将哈希值转换为键和值

  1. where keys is period_id 密钥是period_id
  2. values is subject_id. 值是subject_id。

Then I looped the values and update the Period. 然后,我循环了值并更新了期间。

It is updating, but the Problem is only the last value 2 is updated, where every subject_id becomes 2, I don't no what happens to 3(the first value), only the last value is updated. 它正在更新,但是问题是仅最后一个值2被更新,每个subject_id变为2,我对3(第一个值)没有什么影响,仅最后一个值被更新。 I am just banging my head to solve this problem for two days. 我只是想解决这个问题两天。 I am new to rails, Please be kind. 我是新手,请客气。 Thanks for the answer in advance. 预先感谢您的回答。

You say you have a hash where the keys are period_id and the values are subject_id . 您说您有一个哈希,其中键是period_id ,值是subject_id Assuming your hash name is period_and_subjects , you want to do this: 假设您的哈希名称为period_and_subjects ,则需要执行以下操作:

Period.update(period_and_subjects.keys, period_and_subject.values)

So, if your period_and_subjects hash looks like {1 => 2, 4 => 5} , it would update the period with id 1 with the subject with id 2 and the period with id 4 with the subject with id 5. 因此,如果您的period_and_subjects哈希看起来像{1 => 2, 4 => 5} ,它将使用ID为2的主题更新ID为1的期间,并将ID为5的主题更新为ID 4。

Look at the docs for update . 查看文档以进行update

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM