How to use the find method for composite primary keys in ruby ​​on rails?

advertisements

I have a table called SubElement.

It has two primary keys : Element_Code, Sub_Element_Code

In my view, when i try to do something like the following

<%
  sub_element_model = Condition::SubElement
  sub_element = @sub_element_code.nil? ? sub_element_model.new : sub_element_model.find(@sub_element_code)
  if sub_element.persisted?
    @element_code = sub_element.Element_Code
    f.object.Sub_Element_Code = @sub_element_code
  end
%>

I got an error after selected the sub_element_value like

["4"]: Incorrect number of primary keys for Condition::SubElement: [:Element_Code, :Sub_Element_Code]

How can i use the find method for two composite primary keys.

Update:

In the form, I have element_code field, sub_element_code and material. But everything should visible once the parent selected. With the help of some javascript I try to finish this. The Main problem of what I could not explain in detail is the form fields are creating by some helper file. It's a very large file and i cant change that. So I am looking for the alternative solution to change the find method for the two composite primary keys to get the value.


You should not be using find (which gets a single record by primary key - which you don't completely have), but rather where (which gets you a collection of records by any field(s) you want):

sub_element = @sub_element_code ?
    SubElement.where(sub_element_code: @sub_element_code).first :
    SubElement.new