ruby on rails - Creating an object and assigning it an associated object to it from a different model -


i have tools , projects in database. projects belong tools & 1 tool has 1 project. have numerous tools in database.

when creating project want able assign tool well. tricky thing tool referenced tool_id in database while users know tool's names.

so when create project want able pass in tool_name , somehow figure out tool , create project proper tool assigned it.

here code far, can see not work. take tool_name in new project form strong params expecting tool_id not tool_name

how solve this?

i have form

<%= form_for [@project], :html => { :multipart => true } |f| %> <div class="form-group">    <%= f.label :name %><br>    <%= f.text_field :name, class:'form-control' %> </div> <div class="form-group">    <%= f.label :tool_name %><br>    <%= f.text_field :tool_name, class:'form-control' %> </div> 

in project controller have following create method , strong parameters

def create     @project = project.new(project_params) end  private  def project_params     params.require(:project).permit(:name, :tool_id) end 

my project table following:

create_table "projects", force: :cascade |t|     t.string  "name"     t.integer "tool_id" end 

my tool table:

create_table "tools", force: :cascade |t|     t.string  "tool_name" end 

in project model have: belongs_to :tool in tool model have: has_one :project

i provide dropdown instead tools available. like:

<%= f.collection_select(:tool_id, tool.all, :id, :name) %> 

if list of tools large might better off autocomplete, depends on application.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -