Rails 7 vanilla-nested gem link to add item not working - html

I am trying to use the vanilla-nested gem, with Rails 7, to add an item in a nested edit form. The link is not work and not action results.
I have tried to follow the example code in the gem test path for rails 7.
Here is the edit view:
activities/edit.html.erb
<div class="container">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<br>
<h1 class="m-0 text-dark">Update Transaction</h1>
</div>
</div>
</div>
</div>
<%= render "form", activity: #activity %>
The form partial:
activities/_form.html.erb
<div class="row no-gutters">
<div class="col-auto">
<%= image_tag '16419114852474091540459891939039.jpeg', class: "main-image",
width: "658", sizes: "(max-width: 767px) 96vw, (max-width: 991px) 354px, 460px", alt: ""
%>
</div>
<div class="col">
<div class="card-block px-2">
<%= form_for activity do |form| %>
<div class="row">
<%= form.label :date_submitted, class: 'col-lg-3 text-right', style: "display: block" %>
<div class="col-lg-2">
<%= form.date_field :date_submitted %>
</div>
</div>
<br>
<div class="row">
<%= form.label :transaction_date, class: 'control-label col-lg-3', style: "display: block" %>
<div class="col-lg-2">
<%= form.date_field :activity_date %>
</div>
</div>
<br>
<div>
<div class="row">
<div class="col-lg-8">
<h3>Transaction Items</h3>
<%= link_to_add_nested(form, :items, '#items') do %>
<span><span> Add Item</span></span>
<% end %>
</div>
</div>
<div id='items'>
<%= form.fields_for :items do |sub_form| %>
<%= render 'item_fields', form: sub_form %>
<% end %>
</div>
</div>
<div>
<%= form.submit 'Save Update', class: "btn btn-primary" %>
</div>
<% end %>
<br>
</div>
</div>
</div>
<div class="card-footer w-100 text-muted">
<div>
<%= link_to "Show this activity", #activity %> |
<%= link_to "Back to activities", activities_path %>
</div>
</div>
The fields partial:
activities/_item_fields.html.erb
<div class="item-fields">
<div class="row">
<div class="col-lg-6">
<%= form.label :amount, style: "display: block" %>
<%= form.text_field :item_amount %>
</div>
<div class="col-lg-4">
<%= form.label :vendor, style: "display: block" %>
<%= form.text_field :vendor %>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-6">
<%= form.label :expense_category, style: "display: block" %>
<%= form.select(:expense_category, #category_choices) %>
</div>
<div class="col-lg-4">
<%= form.label :transaction_type, style: "display: block" %>
<%= form.select(:transaction_type, #transaction_choices) %>
</div>
</div>
<br>
</div>
The Items model
models/item.rb
class Item < ApplicationRecord
belongs_to :activity
end
The Activity model:
models/activity.rb
class Activity < ApplicationRecord
belongs_to :account
belongs_to :user
has_many :items, dependent: :destroy
accepts_nested_attributes_for :items, reject_if: :all_blank
has_one_attached :activity_image
validate :acceptable_image
def acceptable_image
return unless activity_image.attached?
unless activity_image.byte_size <= 5.megabyte
errors.add(:activity_image, "is too big")
end
acceptable_types = ["image/jpeg", "image/png"]
unless acceptable_types.include?(activity_image.content_type)
errors.add(:activity_image, "must be a JPEG or PNG")
end
end
end
The Activities controller
controllers/activities_controller.rb
class ActivitiesController < ApplicationController
before_action :set_activity, only: %i[ show edit update destroy add_item ]
# GET /activities or /activities.json
def index
#activities = Activity.all
end
# GET /activities/1 or /activities/1.json
def show
end
# GET /activities/new
def new
#activity = Activity.new
#activity.items.build
end
# GET /activities/1/edit
def edit
set_transaction_choices
set_category_choices
end
# POST /activities or /activities.json
def create
#activity = Activity.new(activity_params)
respond_to do |format|
if #activity.save
format.html { redirect_to activity_url(#activity), notice: "Activity was successfully created." }
format.json { render :show, status: :created, location: #activity }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #activity.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /activities/1 or /activities/1.json
def update
respond_to do |format|
if #activity.update(activity_params)
format.html { redirect_to activity_url(#activity), notice: "Activity was successfully updated." }
format.json { render :show, status: :ok, location: #activity }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #activity.errors, status: :unprocessable_entity }
end
end
end
# DELETE /activities/1 or /activities/1.json
def destroy
#activity.destroy
respond_to do |format|
format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_activity
#activity = Activity.find(params[:id])
end
# Only allow a list of trusted parameters through.
def activity_params
params.require(:activity).permit(:account_id, :user_id, :date_submitted,
:activity_date, :reviewed, :finalized, :notes, :emailed_question,
items_attributes: [ :id, :item_amount, :vendor,
:expense_category, :transaction_type])
end
def set_transaction_choices
#transaction_choices = [["Expense", 'expense'], ["Revenue", 'revenue']]
end
def set_category_choices
#category_choices = ['Fuel', 'Tolls',
'Repairs and Maintance', 'Plates', 'Truck Insurance',
'Cell Phone', 'Internet', 'Satellite', 'Perdiem Days',
'Office Supplies', 'Professional Services',
'Other expenses', 'Liability Insurnace', 'Health Insurnace',
'Truck Supplies and Equipment',
'Working Clothes and Gear', 'Lease and Rental Fees',
'Taxes and Licenses', 'Travel Expenses',
'Contract Wages', 'Revenue',
'Marketing Fees', 'Subscriptions',
'Software' ]
#category_choices.sort!
end
end
The Items controller
controllers/items_controller.rb
class ItemsController < ApplicationController
before_action :set_item, only: %i[ show edit update destroy ]
# GET /items or /items.json
def index
#items = Item.all
end
# GET /items/1 or /items/1.json
def show
end
# GET /items/new
def new
end
# GET /items/1/edit
def edit
end
def add_item
#act = Activity.find(params[:activity_id])
#act.items.create(
activity: #act
)
end
# POST /items or /items.json
# POST /items or /items.json
def create
#item = Item.new(item_params)
respond_to do |format|
if #item.save
format.html { redirect_to edit_activity_path(activity_id), notice: "Item was successfully created." }
#format.json { render :show, status: :created, location: #item }
else
format.html { render :new, status: :unprocessable_entity }
#format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /items/1 or /items/1.json
def update
respond_to do |format|
if #item.update(item_params)
format.html { redirect_to item_url(#item), notice: "Item was successfully updated." }
format.json { render :show, status: :ok, location: #item }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /items/1 or /items/1.json
def destroy
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: "Item was successfully destroyed." }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_item
#item = Item.find(params[:id])
end
# Only allow a list of trusted parameters through.
def item_params
params.require(:item).permit(:activity_id, :item_amount, :vendor, :expense_category, :transaction_type)
end
end
The application.js file:
app/javascript/application.js
import "#hotwired/turbo-rails"
import "controllers"
import "trix"
import "#rails/actiontext"
import * as bootstrap from "bootstrap"
import "custom/main"
import "vanilla-nested";
the importmap.rb
config/importmap.rb
pin "application", preload: true
pin "#hotwired/turbo-rails", to: "turbo.min.js", preload: true
pin "#hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "#hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
pin "trix"
pin "#rails/actiontext", to: "actiontext.js"
pin "vanilla-nested", to: "vanilla_nested.js", preload: true
pin_all_from "app/javascript/custom", under: "custom"

Related

How to insert a button to register a Datetime in Rails

I have this MVC project of a time clock, and I want to do the following configuration on it: that the user just click on a button and register the "clock_in" and click on another button and register the "clock_out" below are the controller, the view and the model.If anyone can help me I will be very grateful
shifts_controller.rb
def create
#shift = Shift.new(shift_params.merge(user: current_user)) # quando criar ja mostra o id
respond_to do |format|
if #shift.save
format.html { redirect_to action: 'show', user_id: current_user, id: #shift, notice: 'Shift was successfully created.' }
format.json { render :show, status: :created, location: #shift }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #shift.errors, status: :unprocessable_entity }
end
end
end
shift.rb
class Shift < ApplicationRecord
attr_accessor :clock_in, :clock_out, :user_id
belongs_to :user
def push_in
self.clock_in = DateTime.now - 3.hours
end
def push_out
self.clock_out = DateTime.now - 3.hours
end
end
_form.html.erb
<%= simple_form_for(#shift, url: url, method: method )do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.time_field :push_in, value: f.object.push_in.strftime("%H:%M") %>
<%= f.date_field :push_in %>
</div>
<div class="form-inputs">
<%= f.time_field :push_out, value: f.object.push_in.strftime("%H:%M") %>
<%= f.date_field :push_out %>
</div>
<div class="form-actions">
<br/><%= f.button :submit %>
</div>
<% end %>

The action 'update' could not be found for JobsController + missing params

I have been working on my startup for a week, after implementing the braintree (sandbox) I can not load params from the form http://0.0.0.0:3000/jobs/new. In the show and index action nothing is simply displayed. When I try to edit the offer http://0.0.0.0:3000/jobs/4/edit I get the error
"The action 'update' could not be found for JobsController".
In the index (http://0.0.0.0:3000/jobs/) in the place title and description is the address from routes. Also missing is an avatar from AvatarUploader which was previously.
offer from http://0.0.0.0:3000/
jobs_controller.rb
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def destroy
#job = Job.find(params[:id])
#job.destroy
end
def set_job
#job = Job.find(params[:id])
end
def index
#jobs = Job.all
fresh_when last_modified:
#jobs.maximum(:updated_at)
if params[:search]
#jobs = Job.search(params[:search]).order("created_at DESC")
else
#jobs = Job.all.order("created_at DESC")
end
if(params.has_key?(:job_type))
#jobs = Job.where(job_type: params[:job_type]).order("created_at desc")
end
# GET /jobs/1
# GET /jobs/1.json
def show
#job = Job.find(params[:id])
end
# GET /jobs/new
def new
#job = current_user.jobs.build
#job = Job.new
end
# GET /jobs/1/edit
def edit
#job = Job.find(params[:id])
end
# POST /jobs
# POST /jobs.json
def create
#job = current_user.jobs.build(#job_params)
job_type = params[:job_type]
job_salary = params[:salary]
job_title = params[:title]
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'Your job listing was purchased successfully!' }
format.json { render :show, status: :created, location: #job }
else
format.html { render :new }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
def update
#job = Job.find(params[:id])
respond_to do |format|
if #job.update(job_params)
format.html { redirect_to #job, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: #job }
else
format.html { render :edit }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
def job_params
params.require(:job).permit(:title, :description, :requirements, :url, :job_type, :location, :job_author, :remote, :apply_url, :avatar, :salary, :multisport_card, :medical_care, :cold_drinks, :parking, :job_category)
end
end
end
end
_form.html.erb
<%= simple_form_for #job, html: { multipart: true } do |f| %>
<div class="field">
<div class="control">
<%= f.input :title, required: true,input_html: { class: "input is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Tytuł stanowiska" %>
</div>
</div>
<div class="field">
<div class="control">
<%= f.input :apply_url, required: true, input_html: { class: "input is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Adres do rekrutacji" %>
</div>
</div>
<div class="number_field">
<div class="control">
<%= f.input :salary, required: true, input_html: { class: "input is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Wynagrodzenie ($) / rok" %>
</div>
</div>
<br>
<div class="columns">
<div class="field column is-4">
<div class="control">
<label class="label">Typ zatrudnienia:</label>
<div class="control has-icons-left">
<span class="select">
<%= f.input_field :job_type, required: true, collection: Job::JOB_TYPES, prompt: "Wybierz typ zatrudnienia", class: "input is-rounded" %>
</span>
<span class="icon is-small is-left">
<i class="fa fa-briefcase"></i>
</span>
</div>
</div>
</div>
<div class="field column is-4">
<div class="control">
<label class="label">Kategoria</label>
<div class="control has-icons-left">
<span class="select">
<%= f.input_field :job_type, required: true, collection: Job::JOB_CATEGORY, prompt: "Wybierz kategorie", class: "input is-rounded" %>
</span>
<span class="icon is-small is-left">
<i class="fa fa-briefcase"></i>
</span>
</div>
</div>
</div>
<div class="column">
<div class="field">
<div class="control">
<%= f.input :location, required: true, input_html: { class: "input is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Lokalizacja" %>
</div>
</div>
</div>
</div>
<div class="field column">
<div class="field">
<div class="control">
<%= f.input :description, required: true, input_html: { class: "textarea is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Opis" %>
</div>
</div>
<div class="field">
<div class="control">
<%= f.input :requirements, required: true, input_html: { class: "textarea is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Wymagania" %>
</div>
</div>
<div class="columns">
<div class="field column">
<div class="control">
<%= f.input :job_author, required: true, input_html: { class: "input is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Firma" %>
</div>
</div>
<div class="field column">
<div class="control">
<%= f.input :url, required: true, input_html: { class: "input is-rounded" }, wrapper: false, label_html: { class: "label" }, label: "Strona Firmy" %>
</div>
</div>
</div>
<div class="columns">
<div class="field column is-4">
<div class="control">
<label class="label">Logo firmy</label>
<div class="file">
<label class="file-label">
<%= f.input :avatar, as: :file, required: false, input_html: { class:"file-input is-rounded job-avatar" }, label: false, wrapper: false %>
<span class="file-cta">
<span class="file-icon"><i class="fa fa-upload"></i></span>
<span class="file-label">Wyślij na serwer</span>
</span>
</label>
</div>
</div>
</div>
<div class="field">
<div class="control">
<label for="job[remote]">
<%= f.input :remote, required: false, input_html: { class: "checkbox is-rounded"}, wrapper: false, label: false %>
Praca zdalna
</div>
<div class="control">
<label for="job[multisport_card]">
<%= f.input :multisport_card, required: false, input_html: { class: "checkbox is-rounded"}, wrapper: false, label: false %>
Karta multisport
</div>
<div class="control">
<label for="job[medical_care]">
<%= f.input :medical_care, required: false, input_html: { class: "checkbox is-rounded"}, wrapper: false, label: false %>
Opieka medycnza
</div>
<div class="control">
<label for="job[cold_drinks]">
<%= f.input :cold_drinks, required: false, input_html: { class: "checkbox is-rounded"}, wrapper: false, label: false %>
Zimne napoje
</div>
<div class="control">
<label for="job[parking]">
<%= f.input :parking, required: false, input_html: { class: "checkbox is-rounded"}, wrapper: false, label: false %>
Parking
</div>
</div>
<div class="column">
<output id="list"></output>
</div>
</div>
<hr />
<%= link_to 'Subscribe to add offer', new_subscription_path %>
<%= f.button :submit, class: "button is-link is-fullwidth is-rounded", value: "Dodaj ofertę pracy" %>
<% end %>
routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
resources :jobs
resource :subscription
resources :meetups
resources :posts do
resources :comments
end
resources :meetups do
resources :discussions
end
devise_for :users
root to: 'welcome#index'
get 'posts', to: 'posts#index'
get '/jobs', to: 'jobs#index'
get '/team', to: 'team#index'
get '/meetups', to: 'meetups#index'
end
repository here <---------------------------
I suggest that you format and indent your code properly (some IDEs even do this automatically). Because if you did, you would have noticed that you nested all methods below the index method into the body of the index method.
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def destroy
#job = Job.find(params[:id])
#job.destroy
end
def set_job
#job = Job.find(params[:id])
end
def index
#jobs = Job.all
fresh_when last_modified: #jobs.maximum(:updated_at)
if params[:search]
#jobs = Job.search(params[:search]).order("created_at DESC")
else
#jobs = Job.all.order("created_at DESC")
end
if(params.has_key?(:job_type))
#jobs = Job.where(job_type: params[:job_type]).order("created_at desc")
end
# GET /jobs/1
# GET /jobs/1.json
def show
#job = Job.find(params[:id])
end
# GET /jobs/new
def new
#job = current_user.jobs.build
#job = Job.new
end
# GET /jobs/1/edit
def edit
#job = Job.find(params[:id])
end
# POST /jobs
# POST /jobs.json
def create
#job = current_user.jobs.build(#job_params)
job_type = params[:job_type]
job_salary = params[:salary]
job_title = params[:title]
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'Your job listing was purchased successfully!' }
format.json { render :show, status: :created, location: #job }
else
format.html { render :new }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
def update
#job = Job.find(params[:id])
respond_to do |format|
if #job.update(job_params)
format.html { redirect_to #job, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: #job }
else
format.html { render :edit }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
def job_params
params.require(:job).permit(:title, :description, :requirements, :url, :job_type, :location, :job_author, :remote, :apply_url, :avatar, :salary, :multisport_card, :medical_care, :cold_drinks, :parking, :job_category)
end
end
end
end
Just fix this to the following version and your create method will be found.
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def destroy
#job = Job.find(params[:id])
#job.destroy
end
def set_job
#job = Job.find(params[:id])
end
def index
#jobs = Job.all
fresh_when last_modified: #jobs.maximum(:updated_at)
if params[:search]
#jobs = Job.search(params[:search]).order("created_at DESC")
else
#jobs = Job.all.order("created_at DESC")
end
if(params.has_key?(:job_type))
#jobs = Job.where(job_type: params[:job_type]).order("created_at desc")
end
end
# GET /jobs/1
# GET /jobs/1.json
def show
#job = Job.find(params[:id])
end
# GET /jobs/new
def new
#job = current_user.jobs.build
#job = Job.new
end
# GET /jobs/1/edit
def edit
#job = Job.find(params[:id])
end
# POST /jobs
# POST /jobs.json
def create
#job = current_user.jobs.build(job_params)
job_type = params[:job_type]
job_salary = params[:salary]
job_title = params[:title]
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'Your job listing was purchased successfully!' }
format.json { render :show, status: :created, location: #job }
else
format.html { render :new }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
def update
#job = Job.find(params[:id])
respond_to do |format|
if #job.update(job_params)
format.html { redirect_to #job, notice: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: #job }
else
format.html { render :edit }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
def job_params
params.require(:job).permit(:title, :description, :requirements, :url, :job_type, :location, :job_author, :remote, :apply_url, :avatar, :salary, :multisport_card, :medical_care, :cold_drinks, :parking, :job_category)
end
end

NoMethodError in CommentsController#new undefined method `text' for #<Comment id: nil, author: nil, created_at: nil, updated_at: nil>

I'm trying to use rails with react, just by adding a comments section to the app i'm working on. The /comments page works. But when I try to make a new comment. I get this error. I went back to the guide I'm using and doesn't explain anything about this. I'm new to rails and react so if someone could help me out I would appreciate it.
Application Trace:
app/views/comments/_form.html.erb:20:in `block in_app_views_comments__form_html_erb__930297241_104622300'
app/views/comments/_form.html.erb:1:in `_app_views_comments__form_html_erb__930297241_104622300'
app/views/comments/new.html.erb:3:in `_app_views_comments_new_html_erb__151456299_104688260'
comments_controller.rb:
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :edit, :update, :destroy]
# GET /comments
# GET /comments.json
def index
#comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
#comment = Comment.new
end
# GET /comments/1/edit
def edit
end
# POST /comments
# POST /comments.json
def create
#comment = Comment.new(comment_params)
respond_to do |format|
if #comment.save
format.html { redirect_to #comment, notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: #comment }
else
format.html { render :new }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /comments/1
# PATCH/PUT /comments/1.json
def update
respond_to do |format|
if #comment.update(comment_params)
format.html { redirect_to #comment, notice: 'Comment was successfully updated.' }
format.json { render :show, status: :ok, location: #comment }
else
format.html { render :edit }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.json
def destroy
#comment.destroy
respond_to do |format|
format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_comment
#comment = Comment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def comment_params
params.require(:comment).permit(:author, :comment_text)
end
end
_form.html.erb:
<%= form_for(#comment) do |f| %>
<% if #comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#comment.errors.count, "error") %> prohibited this comment from being saved:</h2>
<ul>
<% #comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :author %><br>
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :comment_text %><br>
<%= f.text_area :comment_text %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
new.html.erb:
<h1>New Comment</h1>
<%= render 'form' %>
<%= link_to 'Back', comments_path %>
[timestamp]_create_comments.rb:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.string :author
t.text :comment_text
t.timestamps null: false
end
end
end
Seems like the problem originates with your schema/migration. The line:
params.require(:comment).permit(:author, :text)
suggests that you have a column named text, which is a datatype in Rails. You should pick a name like "comment_text" for that column that doesn't echo the name of a datatype.
It's also possible that you transposed the datatype and the column name in your migration.

Rails 4.1: Unable to create multiple answers in form

Want to create a polling app that allows you to create a question with 5 different possible answers (multiple choice).
The user can create a question via the question_form.html.erb followed by possible answers but it only shows me one box , not five.
question_form.html.erb
<%= form_for([ #poll, #question ]) do |f| %>
<% if #question.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% #question.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :kind %><br>
<% #kind_options.each do |option| %>
<label>
<%= f.radio_button :kind, option[1] %>
<%= option[0] %>
</label>
<% end %>
<p>Specify some choices:</p>
<%= f.fields_for :possible_answers do |c| %>
<p>
<%= c.text_field :title, placeholder: "Type your choice", class: "form-control" %>
</p>
<% end %>
</div>
in my questions controller I have added line 5.times { #question.possible_answers.build }
but when i run the program it gives me 1 box to enter the answer not 5?
<div class="actions">
<%= f.submit 'Save', class: "btn btn-primary" %>
</div>
<% end %>
class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
before_action :set_poll
before_action :set_kind_questions
# GET /questions
# GET /questions.json
def index
#questions = Question.all
end
# GET /questions/1
# GET /questions/1.json
def show
end
**# GET /questions/new
def new
#question = #poll.questions.build
5.times { #question.possible_answers.build }
end**
# GET /questions/1/edit
def edit
end
# POST /questions
# POST /questions.json
def create
#question = #poll.questions.build(question_params)
respond_to do |format|
if #question.save
format.html { redirect_to #poll, notice: 'Question was successfully created.' }
format.json { render :show, status: :created, location: #question }
else
format.html { render :new }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /questions/1
# PATCH/PUT /questions/1.json
def update
respond_to do |format|
if #question.update(question_params)
format.html { redirect_to #question, notice: 'Question was successfully updated.' }
format.json { render :show, status: :ok, location: #question }
else
format.html { render :edit }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
#question.destroy
respond_to do |format|
format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
#question = Question.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:title, :kind, :poll_id)
end
**def set_kind_questions
#kind_options = [
[ "Open Answer", "open" ],
[ "Multiple Choice", "choice" ],
]
end**
def set_poll
#poll = Poll.find params[:poll_id] #/polls/1/questions
end
end
If you're working through Build a Polling Application with Rails, the Question model you're most likely using (which you didn't list) is incomplete, so Rails chokes on possible_answers before the controller's Questions#new iterates through the build method. You need to add accepts_nested_attributes_for :possible_answers to the model. Then 5.times { #question.possible_answers.build } will work.
app/models/question.rb
class Question < ActiveRecord::Base
belongs_to :poll
has_many :possible_answers
accepts_nested_attributes_for :possible_answers
end
I've run into a few snags where the author edited code out of sync with his screencasts. You have to look carefully at the diffs on his tut's repo.

Get count of likes on a post in Rails

In my rails application, I am using the gem, socialization.
I just can't figure out how to display the amount of likes!
My post controller :
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
#posts = Post.all(:order => "created_at DESC")
#posts_not_signed_in = Post.all(:order => "created_at DESC")
#post = Post.new
#users = User.all(:order => "created_at DESC")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end
def like
post.liked_by current_user
redirect_to root_path
end
# GET /posts/1
# GET /posts/1.json
def show
redirect_to posts_path
end
# GET /posts/new
# GET /posts/new.json
def new
#post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #post }
end
end
# GET /posts/1/edit
def edit
#post = Post.find(params[:id])
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.build(params[:post])
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render json: #post, status: :created, location: #post }
else
format.html { render action: "new" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.json
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
My user controller :
class UsersController < ApplicationController
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #users }
end
end
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
def follow
#user = User.find(params[:id])
current_user.toggle_follow!(params[:id])
redirect_to root_path
end
def unfollow
#user = User.find(params[:id])
current_user.stop_following(#user)
redirect_to root_path
end
end
My post model :
class Post < ActiveRecord::Base
attr_accessible :status, :author, :username, :id, :user_id, :user, :website, :bio, :skype, :dob, :age, :email, :motto, :follower, :followable, :votes
belongs_to :user
has_many :like
has_many :likes
validates :status, :presence => true
acts_as_likeable
acts_as_votable
end
My user model :
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :user_id, :id, :website, :bio, :skype, :dob, :age, :motto, :follower, :followable
has_many :posts
acts_as_liker
# attr_accessible :title, :body
end
My view :
<% if user_signed_in? %>
<h1 id="welcome" class="nuvo">Welcome <%= current_user.username %>!</h1>
<% else %>
<h1 id="welcome" class="nuvo">Log-In to make some posts!</h1>
<% end%>
<div class="follow-row">
<div class="titan-users nuvo"><h2>BoomIt Users</h2></div>
<div class="user-row nuvo"><%= link_to 'coreypizzle', user_path(1) %> - <%= link_to 'BoomBoard', dashboard_path(1) %></div>
<% #users.each do |user| %>
<div class="user-row nuvo"><%= link_to user.username, user_path(user.id) %> - <%= link_to 'BoomBoard', dashboard_path(user.id) %></div>
<% end %>
</div>
<div class="statuses">
<% if user_signed_in? %><div class="status-form"><%= render 'form' %></div><% end %>
<% if user_signed_in? %>
<% #posts.each do |post| %>
<div class="post">
<div class="tstamp">
<%= image_tag avatar_url_small(post.user), :class => 'gravatar' %>
<strong>Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.username %></strong>
</div>
<div class="status"><%= post.status %></div>
<div class="likearea"><%= link_to 'BoomThis', 'posts/like', :class => 'wtxt nuvo' %> - <%= #post.likes.size %></div>
</div>
<% end %>
<% else %>
<% #posts_not_signed_in.each do |post| %>
<div class="post">
<div class="tstamp">
<%= image_tag avatar_url_small(post.user), :class => 'gravatar' %>
<strong>Posted <%= time_ago_in_words(post.created_at) %> ago by <%= post.user.username %></strong>
</div>
<div class="status"><%= post.status %></div>
</div>
<% end %>
<% end %>
</div>
Any help would be greatly appreciated!
First
has_many :like
has_many :likes
I think you mean just
has_many :likes
So you would do
#likes_num = #post.likes.count
Which will create a query for the number of likes, and not the actually likes themselves.
Old question, but i couldn't find this either.
The correct method call appears to be:
post.likers(User).count
I'm still unsure why you have to pass the model name in, perhaps so you can ask for the number of likes from that class of liker?
This works though.