has many through checkboxes? - ruby-on-rails

I have a many-many relationship with students and organizations. When creating a new student, I want to have a checkbox to select one or more organizations and save that. How do I do this? What does the MVC look like specifically? I can't find any online resource that gives me the whole overview.
Updated code:
in my form partial:
<%= simple_form_for (#student) do |f| %>
<div class="field">
<%= f.label :organization_ids %><br />
<%= collection_check_boxes :student, :organization_ids, Organization.all, :id, :name %>
</div>
<div class="actions">
<button class="btn btn-primary" type="submit">Save</button> <%= link_to "Cancel", :back, {:class=>"btn btn-primary"} %>
</div>
<% end %>
controller:
def update
#student = Student.find(params[:id])
if Student.save_existing(params[:id], params[:student])
flash[:notice] = "Student was successfully updated!"
redirect_to students_path
else
flash[:error] = "Student failed to update."
redirect_to students_path
end
end
def student_params
params.require(:student).permit(:name, :organization_ids => [])
end
student table:
create_table "students", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "organization_id"
t.integer "organization_ids"
end
my problem: when i do #student.organization_ids.inspect, it gives me an empty array meaning that the form didn't save my input form checkboxes

You can use collection_check_boxes. Something like below in your student create form would do.
<div class="field">
<%= f.label :organization_ids %><br />
<%= collection_check_boxes(:student, :organization_ids, Organization.all, :id, :name) %>
</div>

Related

param is missing or the value is empty: item in ruby on rails on windows

I've looked stackoverflow questions regarding to this question(also followed all the instructions given). I am trying to add an new item but I am encountering this error..
Question: Why I am getting this error? What is it?
Controller
class ItemsController < ApplicationController
def index
end
def addItem
end
def create
#item = Item.new(post_params)
#item.save
redirect_to #item
end
def show
#item = Item.find(params[:id])
end
private
def post_params
params.require(:item).permit(:item, :description, :price)
end
end
Add Item view
<%= form_for :post, url: items_create_path do |f| %>
<p>
<%= f.label :Item %><br>
<%= f.text_field :item %>
</p>
<p>
<%= f.label :Description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.label :Price %><br>
<%= f.text_field :price %>
</p>
<p>
<%= f.submit :Submit %>
</p>
<% end %>
<%= link_to 'BACK', items_path %>
Routes
Rails.application.routes.draw do
# URL Controller#method
get '/items/addItem' => 'items#addItem'
get '/items/' => 'items#index'
post '/items/create' => 'items#create'
end
My Table
ActiveRecord::Schema.define(version: 20170323165252) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "items", force: :cascade do |t|
t.string "name"
t.text "description"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
Your items table does not have item field. You are using the name item for name field. So replace item with name and it should work.
Controller
params.require(:item).permit(:name, :description, :price)
Add Item view
<p>
<%= f.label :Item %><br>
<%= f.text_field :name %>
</p>

Event controller not saving to the database

Hi I'm a student in ruby rails. I am trying to create something to save to my database. I can't get it to work.
Here is my form page:
<h1>Create your Event</h1>
<%= form_for #event do |f| %>
<div>
<%= f.label :name %>:
<%= f.text_field :name %><br />
</div>
<div>
<%= f.label :description %>:
<%= f.text_field :description %><br />
</div>
<div>
<%= f.label :location %>:
<%= f.text_field :location %><br />
</div>
<div>
<div class="field">
<%= f.label :date%>
<%= f.date_select :date,
{ order: [:month, :day, :year],
prompt: [ day: 'Select day', month: 'Select month', year: 'Select year' ]} %>
</div>
<br>
<%= f.submit %>
<% end %>
Here is my controller:
class EventsController < ApplicationController
def index
#events = Event.all
end
def show
#event = Event.find(params[:id])
end
def new
#event = Event.new
end
def create
#event = Event.new(event_params)
if #event.save
redirect_to event_index
else
render 'new'
flash[:notice] = "Event not saved"
end
When I click the create event button it doesn't do anything.
my schema
create_table "events", force: :cascade do |t|
t.string "name"
t.string "description"
t.date "date"
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
in the rails console I can see this:
irb(main):001:0> Event.all
Event Load (4.9ms) SELECT "events".* FROM "events"
=> #
irb(main):002:0>
A couple things:
Use #event.save!. If the record cannot be created, the ! will raise a helpful error.
And it doesn't look like you have your event_params defined in your controller.
Also, what does your Event model look like? Any validations?

Choose right method in Controller according to the forms - Rails 5

I have two models: Entreprise & Prospect
create_table "entreprises", force: :cascade do |t|
t.string "name"
t.text "adresse"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "siret"
t.string "numtva"
t.string "tel"
t.integer "prospect_id"
end
create_table "prospects", force: :cascade do |t|
t.string "full_name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "entreprise_id"
end
Prospects belongs_to entreprises, and Entreprise has_many Prospects.
-
My issue :
I have two buttons : Create a new entreprise or reate a new prospect.
I have two way to create a new prospect :
Under my entreprise because an entreprise has_many prospects
Directly from navbar with "create prospect" button
So I have two forms :
If we click on "create prospect" (create method in my controller):
<%= form_for :prospects, url: prospects_path do |f| %>
<p>
<%= f.label :entreprises %><br><br>
<%= f.collection_select :entreprise_id, Entreprise.order(:name),:id,:name, include_blank: true %>
</p><br>
<p>
<%= f.label :full_name %> <br>
<%= f.text_field :full_name %><br>
</p><br>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %><br>
</p><br>
<p>
<%= f.submit %>
</p>
<% end %>
If we create prospect under entreprise ("directcreate" method in my controller) :
<%= form_for([#entreprise, #entreprise.prospects.build]) do |f| %>
<p>
<%= f.label :full_name %> <br>
<%= f.text_field :full_name %><br>
</p><br>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %><br>
</p><br>
<p>
<%= f.submit %>
</p>
<% end %>
My Controller for Prospects :
class ProspectsController < ApplicationController
def index
#prospects = Prospect.all.limit(15).order('created_at DESC')
end
def new
#prospect = Prospect.new
end
def directcreate
#prospect = Prospect.new(entreprise_params)
if #prospect.save
redirect_to #prospect
else
render 'new'
end
end
def create
#entreprise = Entreprise.find(params[:entreprise_id])
#prospect = #entreprise.prospects.create(params[:prospect].permit(:full_name, :email))
redirect_to entreprise_path(#entreprise)
end
def destroy
#entreprise = Entreprise.find(params[:entreprise_id])
#prospect = #entreprise.prospects.find(params[:id])
#prospect.destroy
redirect_to entreprise_path(#entreprise)
end
end
My problème is that the "create" method in my controller is the only one who works.. and not "directcreate" method.
--
QUESTION : How can I do to choose the controller I want according to the form ?
My question is probably not well ask.
FYI I try this in my new.html.erb :
<%= render 'formdirect', :controller => "directcreate" %>
but it doesn't work.
You can try something like this. You just have to explicitly choose your controller action.
<%= form_for([#entreprise, #entreprise.prospects.build], :url => { :action => : directcreate }) do |f| %>
<p>
<%= f.label :full_name %> <br>
<%= f.text_field :full_name %><br>
</p><br>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %><br>
</p><br>
<p>
<%= f.submit %>
</p>
<% end %>

NoMethodError using Rails 4.0 and nested forms with cocoon

I'm learning to use Rails 4.0 and I'm using Cocoon to create nested forms for a simple Polling app.
The user should be able to add a new question and then add as many answers as they'd like.
I've got the nested forms working but when I try to save the Poll and i'm getting an error that says NoMethodError in PollsController#create - undefined method ``answer' for #<Poll:0x007fba59a70dd0>
Here's the relevant information from my Polls_Controller:
before_action :set_poll, only: [:show, :edit, :update, :destroy]
def create
#poll = Poll.new(poll_params)
respond_to do |format|
if #poll.save
format.html { redirect_to #poll, notice: 'Poll was successfully created.' }
format.json { render :show, status: :created, location: #poll }
else
format.html { render :new }
format.json { render json: #poll.errors, status: :unprocessable_entity }
end
end
end
private
def poll_params
params.require(:poll).permit(:question, :expires, answers_attributes: [:id, :answer, :_destroy])
end
Polls Model
class Poll < ActiveRecord::Base
has_many :answers, :class_name => "Answer"
accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true
validates :answer, presence: true
end
And the Answers model
class Answer < ActiveRecord::Base
belongs_to :poll
end
Here are the two .erb partials containing the Poll form and the Answer (nested) form.
_form.html.erb
<%= form_for(#poll) do |f| %>
<% if #poll.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#poll.errors.count, "error") %> prohibited this poll from being saved:</h2>
<ul>
<% #poll.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= f.label :question %><br>
<%= f.text_field :question, class: "form-control" %>
</div>
<div class="form-group" id="answers">
<%= f.fields_for :answers do |answer| %>
<%= render 'answer_fields', f: answer %>
<% end %>
<div class="links">
<%= link_to_add_association 'Add Answer', f, :answers, class: "btn btn-default add-button" %>
</div>
</div>
<div class="form-group">
<%= f.label :expires %><br>
<%= f.datetime_select :expires %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
_answer.html.erb
<div class="nested-fields form-group">
<div class="field">
<%= f.label :answer %>
<br/>
<%= f.text_field :answer, class: "form-control" %>
</div>
<%= link_to_remove_association "remove answer", f, class: "form-button btn btn-default" %>
</div>
I've been staring at this for far too long and even though it's a simple idea, my brain isn't seeing the issue. Any ideas?
Edit Here is my Schema
ActiveRecord::Schema.define(version: 20151104213600) do
create_table "answers", force: :cascade do |t|
t.text "answer"
t.integer "poll_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "answers", ["poll_id"], name: "index_answers_on_poll_id"
create_table "polls", force: :cascade do |t|
t.string "question"
t.datetime "expires"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
I have run into this problem myself, and by pre-building the associated relation, it worked like a charm, doing this:
def new
#poll = Poll.new
#poll.answers.build
end

Rails grab input value on submit in controller

I have a customer model that belongs to user. However, when creating the new customer, the user will not be signed in. Instead I will be assigning the user based on his name attribute.
Here is the customer migration:
create_table :customers do |t|
t.belongs_to :user
t.string :name, null: false
t.date :install_date, null: false
t.decimal :mmr, null: false
t.boolean :sixty_month, default: false
t.boolean :eft, default: false
t.boolean :activation, default: false
t.timestamps
end
I then have a new customer form:
<h1>Create Customer</h1>
<%= form_for #customer do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :install_date %>
<%= f.date_field :install_date %>
</div>
<div>
<%= f.label :mmr %>
<%= f.number_field :mmr %>
</div>
<div>
<%= f.label :sixty_month %>
<%= f.check_box :sixty_month %>
</div>
<div>
<%= f.label :eft %>
<%= f.check_box :eft %>
</div>
<div>
<%= f.label :activation %>
<%= f.check_box :activation %>
</div>
<div>
<%= f.label :users_name %>
<%= f.text_field :users_name %>
</div>
<%= f.submit 'Create Customer' %>
<% end %>
I need to get the users_name field and match it with the associated user and take that users id and assign it to the customers :user_id attribute. In the customers controllers create action so far I have:
#customer.user_id = User.where("name = #{}").id
I need to pull to input from the users_name field in the new customer form and put it into the above code somehow. I just don't know how haha. All help is appreciated!
You will probably want to move this out of the controller and into a helper method but you could do like this:
def create
#customer = Customer.new(customer_params)
if params[:users_name]
user = User.find_by(name: params[:users_name])
#customer.user_id = user.id unless user.nil?
end
if #customer.save
flash[:success] = "Customer created!"
redirect_to #customer
else
render 'new'
end
end
This is assuming you are using Rails 4.

Resources