So I'm learning rails via writing some simple application and in that app I have two types of objects: Tasks and Projects.Sense is that all those objects can be created by user,user must be able to manipulate them and so on.Each task belongs_to project and project has_many tasks.But when I create new project - it already has all tasks from all another projects,so it looks like:
This '123' task was created by simply adding task to 'Project' but same task still appear in 'Another project'.How can I fix this bug and make my task unique?I think something must be added to task or projects model
but I don't know what should I add.
Here are corresponding models and controllers:
Task.rb
class Task < ActiveRecord::Base
belongs_to :project
end
Project.rb
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks, dependent: :destroy
validates :name, presence: true, uniqueness: true
end
tasks_controller.rb
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
# GET /tasks
# GET /tasks.json
def index
#tasks = Task.all
end
# GET /tasks/1
# GET /tasks/1.json
def show
end
# GET /tasks/new
def new
#task = Task.new
end
# GET /tasks/1/edit
def edit
end
# POST /tasks
# POST /tasks.json
def create
#task = Task.new(task_params)
respond_to do |format|
if #task.save
format.html { redirect_to home_url }
format.json { render :show, status: :created, location: #task }
else
format.html { render :home_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tasks/1
# PATCH/PUT /tasks/1.json
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to home_url }
format.json { render :home_url, status: :ok, location: #task }
else
format.html { render :home_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy
#task.destroy
respond_to do |format|
format.html { redirect_to home_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
#task = Task.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def task_params
params.require(:task).permit(:deadline, :name)
end
end
projects_controller.rb
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update, :destroy]
# GET /projects
# GET /projects.json
def index
#projects = Project.all
end
# GET /projects/1
# GET /projects/1.json
def show
end
# GET /projects/new
def new
#project = Project.new
end
# GET /projects/1/edit
def edit
end
# POST /projects
# POST /projects.json
def create
#project = Project.new(project_params)
respond_to do |format|
if #project.save
format.html { redirect_to home_url }
format.json { render :show, status: :created, location: #project }
else
format.html { render :home_url }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /projects/1
# PATCH/PUT /projects/1.json
def update
respond_to do |format|
if #project.update(project_params)
format.html { redirect_to home_url }
format.json { render :show, status: :ok, location: #project }
else
format.html { render :home_url }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
# DELETE /projects/1
# DELETE /projects/1.json
def destroy
#project.destroy
respond_to do |format|
format.html { redirect_to home_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_project
#project = Project.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def project_params
params.require(:project).permit(:name)
end
end
task view -
<% #tasks.each do |task| %>
<div class="row task">
<div class="col-xs-12">
<div class="col-xs-1 checkbox">
<%= check_box_tag 'accept' %>
</div>
<div class="col-xs-8 taskbody">
<%= task.name %>
</div>
<div class="mini-glyph">
<div class="col-xs-1">
<span class="glyphicon glyphicon-arrow-up"></span>
<span class="glyphicon glyphicon-arrow-down"></span>
</div>
<div class="col-xs-1">
<%= link_to edit_task_path(task) do %>
<span class="glyphicon glyphicon-pencil"></span>
<% end %>
</div>
<div class="col-xs-1">
<span><%= link_to " ", task, method: :delete, data: { confirm: 'Are you sure?' }, class:"glyphicon glyphicon-trash" %></span>
</div>
</div>
</div>
</div>
<% end %>
To set the project_id when you create a task, add something like this to your form:
<%= f.select :project_id, options_for_select(Project.choices) %>
then in project.rb
def self.choices
all_projects = []
Project.find_each do |project|
# show the name but save the id
all_projects << [project.name, project.id]
end
all_projects
end
Then change display the tasks with Task.where(project_id: project_id) instead of Task.all as the first two comments suggest.
Related
so, I used CarrierWave gem and followed a railscast demo to get it working, but the image doesn't show on my listing show page.
here's the code on the show page:
<p id="notice"><%= notice %></p>
<p>
<strong>Description:</strong>
<%= #listing.description %>
</p>
<p>
<strong>Price $:</strong>
<%= #listing.price %>
</p>
<p>
<strong>Subcategory:</strong>
<%= Subcategory.find(#listing.subcategory_id).subcategory_name %>
</p>
<p>
<strong>Choose an image to upload:</strong>
<%= image_tag #listing.image_url(:half).to_s %>
</p>
<%= link_to 'Edit', edit_listing_path(#listing) %> |
<%= link_to 'Back', listings_path %> |
<%= link_to 'Home', root_path %>
and here's the controller:
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
before_action :set_options, only: [:new, :edit, :update, :create]
# GET /listings
# GET /listings.json
def search
if params[:category_id].present?
#category = Category.find(params[:category_id])
#subcategory = nil
elsif params[:subcategory_id].present?
#subcategory = Subcategory.find(params[:subcategory_id])
#category = Category.find(#subcategory.category_id)
end
end
def index
#listings = Listing.all
end
# GET /listings/1
# GET /listings/1.json
def show
end
# GET /listings/new
def new
#listing = Listing.new
end
# GET /listings/1/edit
def edit
end
# POST /listings
# POST /listings.json
def create
#listing = Listing.new(listing_params)
respond_to do |format|
if #listing.save
format.html { redirect_to #listing, notice: 'Listing was successfully created.' }
format.json { render :show, status: :created, location: #listing }
else
format.html { render :new }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /listings/1
# PATCH/PUT /listings/1.json
def update
respond_to do |format|
if #listing.update(listing_params)
format.html { redirect_to #listing, notice: 'Listing was successfully updated.' }
format.json { render :show, status: :ok, location: #listing }
else
format.html { render :edit }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /listings/1
# DELETE /listings/1.json
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url, notice: 'Listing was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.find(params[:id])
end
def set_options
#options_for_select_ary = Subcategory.all.collect {|subcategory| [ subcategory.subcategory_name, subcategory.id ] }
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:id, :description, :price, :subcategory_id)
end
end
and finally the model:
class Listing < ApplicationRecord
attr_accessor :image, :remote_image_url
belongs_to :category, optional: true
belongs_to :subcategory, optional: true
belongs_to :delivery, optional: true
belongs_to :user, optional: true
mount_uploader :image, AvatarUploader
end
so, my question is, how do I get the image to show up in the listing once it's been created?
I can add in my AvatarUploader class in an edit if you need to see the carrierwave code....
I'm trying to create a form for task in my app.App has two entities:
Project belongs_to User
Task belongs_to Project
But I get this error in my view when I'm trying to create this (pretty basic) form
No route matches {:action=>"index", :controller=>"tasks"} missing required keys: [:project_id]
Here is a part of my view with this form
<div class="glyphicon glyphicon-plus col-xs-1 left_plus" ></div>
<div class="col-xs-10" >
<%= form_for [#project, #task],url: project_tasks_path do |f| %>
<%= f.input :body,class: 'form-control' %>
<%= f.submit 'Add task', class: 'btn' %>
<% end %>
And here is the project controller:
class ProjectsController < ApplicationController
before_action :load_project, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def index
#projects = current_user.projects unless current_user.nil?
#task = Task.find_by(params[:project_id])
end
def show
#task = #project.tasks.build
end
def new
#project = current_user.projects.new
end
def edit
end
def create
#project = current_user.projects.create(project_params)
if #project.save
redirect_to root_path
else
render :new
end
end
def update
if #project.update(project_params)
redirect_to #project
else
render :edit
end
end
def destroy
#project.destroy
redirect_to projects_path
end
private
def load_project
#project = Project.find(params[:id])
end
def project_params
params.require(:project).permit(:name, :user_id)
end
end
And the tasks controller:
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def index
#tasks = Task.where(project_id: project_id)
end
def show
project = Project.find_by(id: params[:project_id])
#task = Task.new(project: project)
end
def new
project = Project.find_by(id: params[:project_id])
#task = Task.new(project: project)
end
def edit
project = Project.find_by(id: params[:project_id])
#task = Task.new(project: project)
end
def references
respond_to do |format|
if #task.valid?
format.html { redirect_to root_url }
format.json { render :show, status: :created, location: #task }
else
format.html { render :home_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def create
#project = Project.find_by(id: params[:project_id])
#task = #project.tasks.create(task_params)
respond_to do |format|
if #task.valid?
format.html { redirect_to root_url }
format.json { render :show, status: :created, location: #task }
else
format.html { render :home_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to root_url }
format.json { render :home_url, status: :ok, location: #task }
else
format.html { render :root_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def edit
end
def destroy
#task.destroy
respond_to do |format|
format.html { redirect_to root_url }
format.json { head :no_content }
end
end
private
def set_task
#task = Task.find(params[:id])
end
def task_params
params.require(:task).permit(:deadline, :body, :project_id)
end
end
The routes file:
devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'projects#index'
resources :projects do
resources :tasks
end
And my routes:
projects#index
project_tasks GET /projects/:project_id/tasks(.:format) tasks#index
POST /projects/:project_id/tasks(.:format) tasks#create
new_project_task GET /projects/:project_id/tasks/new(.:format) tasks#new
edit_project_task GET /projects/:project_id/tasks/:id/edit(.:format) tasks#edit
project_task GET /projects/:project_id/tasks/:id(.:format) tasks#show
PATCH /projects/:project_id/tasks/:id(.:format) tasks#update
PUT /projects/:project_id/tasks/:id(.:format) tasks#update
DELETE /projects/:project_id/tasks/:id(.:format) tasks#destroy
projects GET /projects(.:format) projects#index
POST /projects(.:format) projects#create
new_project GET /projects/new(.:format) projects#new
edit_project GET /projects/:id/edit(.:format) projects#edit
project GET /projects/:id(.:format) projects#show
PATCH /projects/:id(.:format) projects#update
PUT /projects/:id(.:format) projects#update
DELETE /projects/:id(.:format) projects#destroy
Can somebody please help me to clarify where is the problem and what is the problem?
The problem is with your TasksController#index action. What is project_id there? For accessing a project's tasks, the project needs to exist in the first place. And not just that. To access any CRUD action on tasks, a project has to exist first.
Modify your TasksController as
class TasksController < ApplicationController
before_action :set_project
before_action :set_task, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
def index
#tasks = #project.tasks
end
def show
#makes use of set_task
end
def new
#task = #project.tasks.new
end
def edit
end
def references
respond_to do |format|
if #task.valid?
format.html { redirect_to root_url }
format.json { render :show, status: :created, location: #task }
else
format.html { render :home_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def create
#task = #project.tasks.create(task_params)
respond_to do |format|
if #task.valid?
format.html { redirect_to root_url }
format.json { render :show, status: :created, location: #task }
else
format.html { render :home_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to root_url }
format.json { render :home_url, status: :ok, location: #task }
else
format.html { render :root_url }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def destroy
#task.destroy
respond_to do |format|
format.html { redirect_to root_url }
format.json { head :no_content }
end
end
private
def set_project
#project = current_user.projects.find(params[:project_id]
end
def set_task
#task = #project.tasks.find(params[:id])
end
def task_params
params.require(:task).permit(:deadline, :body, :project_id)
end
end
Since we have defined a before_action set_project, #project will be available to all methods. Note that set_projectfinds the project from the projects created by the current user.
In the ProjectsController#index, you won't actually get a value for params[:project_id]. Modify your index action to
def index
#projects = current_user.projects unless current_user.nil?
end
And I don't understand your show method. The build method is actually used to create a in-memory representation of an object. The show method of projects_controller can be used to display the project along with its tasks. If this is what you need, change you show action in ProjectsController to
def show
##project is available from load_project
#tasks = #project.tasks
end
You could also modify your load_project project as
def load_project
begin
#project = Project.find(params[:id]) #raises an exception if project not found
rescue ActiveRecord::RecordNotFound
redirect_to projects_path
end
end
To know more about rescuing exceptions, see Begin, Rescue and Ensure in Ruby?
For more, see http://blog.8thcolor.com/en/2011/08/nested-resources-with-independent-views-in-ruby-on-rails/
If the form to create a new task is in projects/index.html.erb you should make a #task variable available to the view; try to change the index action as follow:
def index
#projects = current_user.projects unless current_user.nil?
#task = Task.new
end
The problem is with the url for submitting the form. If you check your rake routes you'd see that all your task routes would be nested under projects, therefore in passing the url option, you should have something like:
<div class="glyphicon glyphicon-plus col-xs-1 left_plus" ></div>
<div class="col-xs-10" >
<%= form_for [#project, #task],url: project_tasks_path(#project) do |f| %>
<%= f.input :body,class: 'form-control' %>
<%= f.submit 'Add task', class: 'btn' %>
<% end %>
or even better, I think you should be able to do that without passing the url option:
<div class="glyphicon glyphicon-plus col-xs-1 left_plus" ></div>
<div class="col-xs-10" >
<%= form_for [#project, #task] do |f| %>
<%= f.input :body,class: 'form-control' %>
<%= f.submit 'Add task', class: 'btn' %>
<% end %>
UPDATE
def index
project = Project.find(params[:project_id])
#projects = ProjectsViewPresenter.new(project)
end
# presenters/projects_view_presenter.rb
class ProjectsViewPresenter
attr_reader :project
def initialize(project)
#project = project
end
def tasks
#tasks ||= project.tasks
end
def task
#task ||= tasks.new
end
end
Your form_for would now be like this:
<div class="glyphicon glyphicon-plus col-xs-1 left_plus" ></div>
<div class="col-xs-10" >
<%= form_for [#project.project, #project.task] do |f| %>
<%= f.input :body,class: 'form-control' %>
<%= f.submit 'Add task', class: 'btn' %>
<% end %>
sorry for this question but I'm struggling with this issue for hours now and can't find the answer anywhere.
Here is the thing, I have a rails app with "Reservation" and "Space" models with the following relations:
class Reservation < ActiveRecord::Base
belongs_to :space
belongs_to :user
end
class Space < ActiveRecord::Base
belongs_to :condo
has_many :reservations
end
When the user creates a new Reservation, in the form he gets to choose from a dropdown (f.select) the spaces available for him. The f.select in the form look like this:
<div class="field">
<%= #user_spaces = current_user.condo.spaces
f.select :space_id,
options_from_collection_for_select(#user_spaces, :id, :name), :prompt => "Select space"
%>
</div>
That select it supose to assign a value to the key "space_id" in the Reservation that is being created (column's table is created). But when I check the last reservation in Rails console, space_id value is "nil". What am I doing wrong?
Thank you very much for your help
Reservation controller file:
class ReservationsController < ApplicationController
before_action :set_reservation, only: [:show, :edit, :update, :destroy]
# GET /reservations
# GET /reservations.json
def index
#reservations = Reservation.all
end
# GET /reservations/1
# GET /reservations/1.json
def show
end
# GET /reservations/new
def new
#reservation = Reservation.new
end
# GET /reservations/1/edit
def edit
end
# POST /reservations
# POST /reservations.json
def create
#reservation = Reservation.new(reservation_params)
#user = current_user.id
#reservation.user_id = #user
respond_to do |format|
if #reservation.save
format.html { redirect_to #reservation, notice: 'Reservation was successfully created.' }
format.json { render :show, status: :created, location: #reservation }
else
format.html { render :new }
format.json { render json: #reservation.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /reservations/1
# PATCH/PUT /reservations/1.json
def update
respond_to do |format|
if #reservation.update(reservation_params)
format.html { redirect_to #reservation, notice: 'Reservation was successfully updated.' }
format.json { render :show, status: :ok, location: #reservation }
else
format.html { render :edit }
format.json { render json: #reservation.errors, status: :unprocessable_entity }
end
end
end
# DELETE /reservations/1
# DELETE /reservations/1.json
def destroy
#reservation.destroy
respond_to do |format|
format.html { redirect_to reservations_url, notice: 'Reservation was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_reservation
#reservation = Reservation.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def reservation_params
params.require(:reservation).permit(:eventdate)
end
end
Space controller file:
class SpacesController < ApplicationController
before_action :set_space, only: [:show, :edit, :update, :destroy]
# GET /spaces
# GET /spaces.json
def index
#spaces = Space.all
end
# GET /spaces/1
# GET /spaces/1.json
def show
end
# GET /spaces/new
def new
#space = Space.new
end
# GET /spaces/1/edit
def edit
end
# POST /spaces
# POST /spaces.json
def create
#space = Space.new(space_params)
respond_to do |format|
if #space.save
format.html { redirect_to #space, notice: 'Space was successfully created.' }
format.json { render :show, status: :created, location: #space }
else
format.html { render :new }
format.json { render json: #space.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /spaces/1
# PATCH/PUT /spaces/1.json
def update
respond_to do |format|
if #space.update(space_params)
format.html { redirect_to #space, notice: 'Space was successfully updated.' }
format.json { render :show, status: :ok, location: #space }
else
format.html { render :edit }
format.json { render json: #space.errors, status: :unprocessable_entity }
end
end
end
# DELETE /spaces/1
# DELETE /spaces/1.json
def destroy
#space.destroy
respond_to do |format|
format.html { redirect_to spaces_url, notice: 'Space was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_space
#space = Space.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def space_params
params.require(:space).permit(:name)
end
end
And full Reservation Form:
<%= form_for(#reservation) do |f| %>
<% if #reservation.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#reservation.errors.count, "error") %> prohibited this reservation from being saved:</h2>
<ul>
<% #reservation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :eventdate %><br>
<%= f.date_select :eventdate %>
</div>
<div class="field">
<%= #user = current_user.condo.spaces
f.select :space_id,
options_from_collection_for_select(#user, :id, :name), :prompt => "Select space"
%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
pretty sure you need to permit the space_id attribute in your strong params.
def reservation_params
params.require(:reservation).permit(:eventdate, :space_id)
end
whats happening is that when you go to create a reservation, youre passing in set of params, that is the output of reservation_params
#reservation = Reservation.new(reservation_params)
if space_id is not being permitted in your strong params, then it will be nil when created.
if this is not the issue, can you post what params are getting to the server, and what the output of reservation_params are.
I'm trying to be on that page right before the checkout, where you can modify the quantity and update all the prices accordingly. Now my "Update" button, updates 'something' but it's not what i'm trying to achieve, it sends me on a line_items show page that i don't even want to have (i'm keeping it for now to avoid the missing template error). The rails documentation isn't helping me ... well anyway, the code is this
<ul>
<% #cart.line_items.each do |item| %>
<%= form_for(item) do |f| %>
<li><%= f.number_field :quantity, :value => item.quantity %> x <%= item.product.name %>
<%= item.total_price %> </li>
<% end %>
<%= submit_tag "Update" %>
<% end %>
<br><strong>Total Price:</strong> <%= #cart.total_price %>
</ul>
<%= button_to "Checkout", new_order_path, method: :get, data: { confirm: "Are you sure?" } %>
<%= button_to 'Empty cart', #cart, method: :delete, data: { confirm: 'Are you sure?' } %>
<%= link_to 'Back', categories_path %>
Thank you !
edited
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create, :update, :destroy]
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
# GET /line_items
# GET /line_items.json
def index
#line_items = LineItem.all
end
# GET /line_items/1
# GET /line_items/1.json
def show
end
# GET /line_items/new
def new
#line_item = LineItem.new
end
# GET /line_items/1/edit
def edit
end
# POST /line_items
# POST /line_items.json
def create
product = Product.find(params[:product_id])
#line_item = #cart.add_product(product.id)
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item.cart, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: #line_item }
else
format.html { render :new }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
respond_to do |format|
if #line_item.update(line_item_params)
format.html { redirect_to #cart, notice: 'Line item was successfully updated.' }
format.json { render :show, status: :ok, location: #line_item }
else
format.html { render :edit }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
#line_item.destroy
respond_to do |format|
format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
#line_item = LineItem.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def line_item_params
params.require(:line_item).permit(:product_id, :cart_id, :order_id)
end
end
Just do redirect after you update an item. And provide correct line_item_update_params method that permites quantity param. Your controller should look like that:
class ItemsController < ApplicationController
def update
item = Item.find(params[:id])
item.update(line_item_update_params)
redirect_to :back # this is the key line of code
end
...
private
# it is used for creating
def line_item_params
params.require(:line_item).permit(:product_id, :cart_id, :order_id)
end
# it is used for updating
def line_item_update_params
params.require(:line_item).permit(:quantity)
end
...
end
I'm fairly new to rails, building my first app. I'm running rails 4 w/ bootstrap 3. I'm trying to get a complex form to work. I have two models:
class Employee < ActiveRecord::Base
belongs_to :company
belongs_to :user, :through => :company
has_one :position
accepts_nested_attributes_for :position
end
class Position < ActiveRecord::Base
belongs_to :employees
accepts_nested_attributes_for :employees
end
I have a form where the User can create a new job title (Position Model) and select the employees (Employees Model) that position will be applied to. Basically it's a single form that will add fields to 2 different database tables (Position and Employee).
This is my view:
<%= simple_form_for(#position) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :job_title %>
<%= f.input :job_description %>
</div>
<%= f.fields_for :Employee do |f| %>
<%= f.input :employee_title, label: "Apply to:", collection: Employee.all, label_method: :first_name, as: :check_boxes %>
<% end %>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Below are the controllers:
class PositionsController < ApplicationController
before_action :set_position, only: [:show, :edit, :update, :destroy]
# GET /positions
# GET /positions.json
def index
#positions = Position.all
end
# GET /positions/1
# GET /positions/1.json
def show
end
# GET /positions/new
def new
#position = Position.new
end
# GET /positions/1/edit
def edit
end
# POST /positions
# POST /positions.json
def create
#position = Position.new(position_params)
respond_to do |format|
if #position.save
format.html { redirect_to #position, notice: 'position was successfully created.' }
format.json { render action: 'show', status: :created, location: #position }
else
format.html { render action: 'new' }
format.json { render json: #position.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /positions/1
# PATCH/PUT /positions/1.json
def update
respond_to do |format|
if #position.update(position_params)
format.html { redirect_to #position, notice: 'position was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #position.errors, status: :unprocessable_entity }
end
end
end
# DELETE /positions/1
# DELETE /positions/1.json
def destroy
#position.destroy
respond_to do |format|
format.html { redirect_to positions_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_position
#position = Position.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def position_params
params.require(:position).permit(:position_title, :position_description, :position_create_date)
end
end
class EmployeesController < ApplicationController
# encoding: UTF-8
before_action :set_employee, only: [:show, :edit, :update, :destroy]
# GET /employees
# GET /employees.json
def index
#employees = Employee.all
end
# GET /employees/1
# GET /employees/1.json
def show
end
# GET /employees/new
def new
#employee = Employee.new
end
# GET /employees/1/edit
def edit
end
# POST /employees
# POST /employees.json
def create
#employee = Employee.new(employee_params)
respond_to do |format|
if #employee.save
format.html { redirect_to #employee, notice: 'Employee was successfully created.' }
format.json { render action: 'show', status: :created, location: #employee }
else
format.html { render action: 'new' }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /employees/1
# PATCH/PUT /employees/1.json
def update
respond_to do |format|
if #employee.update(employee_params)
format.html { redirect_to #employee, notice: 'Employee was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1
# DELETE /employees/1.json
def destroy
#employee.destroy
respond_to do |format|
format.html { redirect_to employees_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
#employee = Employee.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
params.require(:employee).permit(:first_name, :last_name, :employee_title)
end
end
The problem I'm facing is I get the form to render perfectly, but when I submit it, only fields that belong to the Position model get recorded. The :employee_title stays blank. Any suggestions what the problem is?
Thank you!!
Too many points to fit in a comment:
belongs_to :employees should be singular: belongs_to :employee
Your fields_for should be like (differentiate the ff from parent form):
<%= f.fields_for :Employee do |ff| %>
<%= ff.input :employee_title, label: "Apply to:", collection: Employee.all,
label_method: :first_name, as: :check_boxes %>
<% end %>
If it doesn't work, supply your controller also and I'll update my answer.
Edit:
After seeing your controllers, it seems most likely to be case of unpermitted params.
In position_controller.rb add employee params to position params
def position_params
params.require(:position).permit(:position_title, :position_description, :position_create_date, employees_attributes: [:first_name, :last_name, :employee_title])
end