I want to update the subject_id
field in Period Model .Where the period loop will be inside the Form. 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
. So, How can I update it.
In my Show.html.erb I has
<%= 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
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
#Parameters: {"utf8"=>"✓", "authenticity_token"=>"8SNaUIQ6ZwjYOqBX07QYyVJsbuvYTL2TotSqIg0yj98nYXq5XqJ5XRHqlCvl1aw0lLg9vowyDOl3Hhm+hYDaOA==", "id"=>{"1"=>"3", "4"=>"2"}, "commit"=>"Save changes"}
Then I converted the hash to keys and values
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. 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
. Assuming your hash name is period_and_subjects
, you want to do this:
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.
Look at the docs for update
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.