ruby - Rails: belongs_to association through a form not populating -
i'm working on controller class, project
. has belongs_to
relationship client
.
i'm not sure why happening, when create new project through form, has name
assigned it, no fee
, no client_id
.
here's relevant code:
project controller
class projectscontroller < applicationcontroller def index end def show end def new @project = project.new end def edit end def create @project = project.new(project_params) if @project.save redirect_to projects_url else render 'new' end end def update end def destroy end private def project_params params.require(:project).permit(:name, :feee, :client_id) end end
projects/new view
<div id="newproject-form"> <h1>create project</h1> <%= form_for @project |p| %> <div id="newproject-form-input"> <ul> <li><%= p.label :name, "project name: " %><br> <%= p.text_field :name, size: 40 %></li> <li><%= p.label :fee, "fee: " %><br> <%= p.text_field :fee %></li> <li><%= p.label :client, "client name: " %><br> <%= collection_select(:client_id, :name, current_user.clients, :id, :name) %></li> <li><%= p.submit "create project", class: "form-button" %>, or <%= link_to "cancel", root_path %></li> </ul> </div> <% end %> </div>
project model
class project < activerecord::base belongs_to :client end
you have call collection_select
on form builder:
# change <%= collection_select(:client_id, :name, current_user.clients, :id, :name) %> # <%= p.collection_select(:client_id, current_user.clients, :id, :name) %>
by using formbuilder p
telling collection_select
editing project object (see p.object
return object of form builder).
if @ collection_select
documentation (http://apidock.com/rails/actionview/helpers/formoptionshelper/collection_select):
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
if call collection_select
own (not form builder, provided form_for
method), have give first argument object's name. in case, have been collection_select(:project, :client_id, #etc.)
generate params params[:project][:client_id]
.