开发者

Add existing objects to another object (Ruby on Rails)

开发者 https://www.devze.com 2023-02-04 05:35 出处:网络
I have an Item model and a Cycle model.The item model belongs to cycle, and cycle has many items.The item model has a barcode value and cycle_id value.

I have an Item model and a Cycle model. The item model belongs to cycle, and cycle has many items. The item model has a barcode value and cycle_id value.

I want to have a show cycle template that has 10 blank fields for entering barcode values. Assume 100 items (with barcode values but no cycle_id) already exist in the database. When the barcode values are entered in the fields, the application should pull each entered barcode value and update the associated item with the cycle_id of t开发者_如何学运维he currently selected cycle.

This may be too broad a question, but I've been spinning in circles for hours and I don't even know where to begin. Any help is greatly appreciated. Thanks!


In your cycles new/edit form, I would add ten empty input boxes somewhere in your form. Not the greatest example of markup, but something like this:

<% 10.times do %>
  <input name="barcodes[]" />
<% end %>

Then in your cycles controller, I would find the cycle, then add all the barcodes that they entered. I'm assuming you don't wan them to create new barcodes if they don't exist. (This is Rails 3 syntax)

def update
  @cycle = Cycle.find(params[:id])

  barcodes = Item.where(:barcode => params[:barcodes])
  @cycle.barcodes = barcodes

  @cycle.save
end


Suppose you want to add Items with barcode ids 1, 2, 3, 4 to Cycle with id 1. You could either do

cycle = Cycle.find(1)
[1, 2, 3, 4].each do |barcode|
   item = Items.where(:barcode => barcode)
   cycle.items << item
end
cycle.save

or do

cycle = Cycle.find(1)
[1, 2, 3, 4].each do |barcode|
   item = Items.where(:barcode => barcode)
   item.cycle = cycle
   item.save
end
0

精彩评论

暂无评论...
验证码 换一张
取 消