Question

I'm new in Rails and seek the trail to Rails way.

Now i'm seekeng the way to use values from related model in my form. As a example, i create two models with *has_one* relationship. Master table "Products" has a field "unit_id" - id of item from related table "Units".

To clarify: The items from model Products has attribute "unit". One product has one attribute unit. The items from model Units are unique and one item unit may belongs to many items in products.

In my form i want to select unit for new Product, i can open the form for units#index, but how i can return and use selected item in caller form?

Code pieces:

1. Model Products:

class Product < ActiveRecord::Base
# ... 
 belongs_to :unit
end

2. Model Units: (it have no code)

class Unit < ActiveRecord::Base
end

3. Template for use the request to related form:

<%= form_for(@product) do |product_form| %>
  ...
  <%= product_form.label :"#{t('unit')}:"%>
  <%= link_to t('unit_select'), units_path%>
  ...
 <div class="actions">
  <%= product_form.submit %>
 </div>
<% end %>

4. Template for form with index of units and from which i want do a choice:

<%@units.each do |unit|%>
 <a href="<%=units_path%>">
  <div>
   <%= unit.shortname %>
   <%= unit.fullname %>
   <%= unit.okei %>
  </div>
 </a>
<%end%>

And my question is: How i must do it? How i can return and use the selected item from Units table?

P.S. sorry for my english. P.P.S. I have example images, but no have the reputaion for include them to my question: https://plus.google.com/photos/101112417211111476248/albums/5848798001333173089/5889575276122513954?banner=pwa&pid=5889575276122513954&oid=101112417211111476248

https://plus.google.com/photos/101112417211111476248/albums/5848798001333173089/5889575270731602306?banner=pwa&pid=5889575270731602306&oid=101112417211111476248

Was it helpful?

Solution

I will give you 3 different options:

1 - The best solution would be to have in your form the list of units and you select there IMO. Easier to implement and a better experience for the user.

2 - Add a hidden_field in your form product_form.unit_id. Then you could use http://lokeshdhakar.com/projects/lightbox2/ to show the units and add a javascript to it that when user click on a unit it will close the lightbox and update the hidden_field value with the id of unit

3 - Add a link to the units in the units page that will redirect to the form page passing the unit_id param then in the controller you do something like this: @product.unit = Unit.find(params["unit_id"] if params["unit_id"].present?. But this way you're going to lose the previous changed data, certainly not a good solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top