Home>

There is a list page of prefectures like WEB secretary and homes, and I want to give each prefecture information about the company.
It's like displaying the data you have in a list by linking prefectures.
Prefectures are Prefecture models and each data is Company model.
The Prefecture and Company models have a one-to-N association.
An error appeared when sending company information, and I didn't know how to write it in the controller to get the id of Prefecture.
Prefecture information is described in the Prefecture model in enum.
The data itself is written directly in seeds.
Please let us know if there is something better about the design besides the error message.

Couldn't find Prefecture without an ID
Corresponding source code

Prefecture.index

<% = form_for (@company, url: admins_companies_path) do | f |%>
      <% #<% = f.hidden_field: prefecture_id ,: value =>@ prefectures.id%>
        
           Added listed companies 
        
        
        <p>Select a prefecture</p>
        <% = f.select: prefecture_id, Prefecture.prefecture_names%>
        <% #<% = f.select: prefecture_id, options_for_select (Prefecture.prefecture_names)%>
        <p>Enter the company name</p>
        <% = f.text_field: company_name%>
        <p>Fill in the description</p>
        <% = f.text_area: description%>
          
          <% = f.attachment_field: image%>
          
        
      <% = f.submit'Create Company'%>
      <% end%>
class Admins :: CompaniesController</pre>
<pre><code>class Admins :: PrefecturesController</pre>
<p><br />
Prefecture.rb</p>
<pre><code>class Prefecture</pre>
<p><br />
route</p>
<pre><code>namespace: admins do
    resources: prefectures, only: [: index,: show,: create]
    resources: companies
  end
  • Answer # 1

    params [: prefecture_id]Looks empty.
    The value submitted from the form isparams [: company] [: prefecture_id]Because it should be in

    @prefecture = Prefecture.find (params [: company] [: prefecture_id])

    If you are yourselfcompany_paramsToprefecture_idIncluding.

    def create
      company = Company.new (company_params)
      if company.save
        lash [: notice] ='successfully'
        redirect_to admins_prefectures_path
      end
    end
    def company_params
      params.require (: company) .permit (: company_name,: description,: image,: prefecture_id)
    end

  • Answer # 2

    An error appeared when sending company information, and I didn't know how to write it in the controller to get the id of Prefecture.

    Isn't there a need for it? Simplyprefecture_idPut inCompanyTosave saveIf you do, laterPrefecture #companiesYou can list it with.