1

Part 1: What i want is to fetch records of two tables in one collection select. Later, i want to perform search based on selected item.

So far i have managed to get the records in this manner in one select:

Controller:

@result1 = Model1.all
@result2 = Model2.all
@all = @result2 | @result1

View:

<%= collection_select :id,:id,@all, :id, :id,{prompt: "All Templates"} %>

The problem here is i want to display the name form Model1 and type from Model2.

Part 2 If the user selects the name, i want to get record from Model1 and if the type is selected, i want to get records form Model2.

All i am able to get is the id of both the models in one collection select. I am out of ideas. Let me know if any more details are required. Any help is appreciated. Thanks.

Aakanksha
  • 956
  • 1
  • 13
  • 26

1 Answers1

1

You've supplied :id to collection_select for the text_method. Check the docs to see how this helper works.

One solution would be to create an 'alias' method in each of your models which you can then call in collection_select:

model1.rb

class Model1
  def text_value
    name
  end
end

model2.rb

class Model2
  def text_value
    type
  end
end

I've named the method, text_value, for demonstration purposes. You may need to come up with a different name for that attribute.

Incidentally type as an attribute is reserved for Single Table Inheritance tables so it would be better to use a different attribute name.

in the view

<%= collection_select :id,:id, @all, :id, :text_value, {prompt: "All Templates"} %>
margo
  • 2,927
  • 1
  • 14
  • 31
  • that worked like a charm man. Thanx a ton. Could you please help me figure out the part 2 of the question as well. I seem to be lost. I just have a collection select on whose selection, the records appears. So from what i get, i have to use ajax call. So, if name is selected, the url should be of Model1 and if type is selected, the url would be Model2. How would i differentiate? – Aakanksha Apr 18 '16 at 09:35
  • You'll need to modify where the form posts, again using a method that is more generic. It would be best if you started another question and showed more code including the view with the form code. – margo Apr 18 '16 at 09:53
  • i'll give a try to the ideas i think will work for me first. If i don't get the results as desired, i'll sure get back here with another question and expect you to be there to help. Thanx :) – Aakanksha Apr 18 '16 at 09:58