This my first ruby on rails application.
Model Location and Post, Location has many post.I create location as tree structure with ancestry gem.
class Post < ActiveRecord::Base
belongs_to :location, :counter_cache => true
end
class Location < ActiveRecord::Base
include Tree
has_ancestry :cache_depth => true
has_many :posts
end
This my Post Controller
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
#posts = Post.all
end
def show
end
def new
#post = Post.new
end
def edit
end
def create
#post = Post.new(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: #post }
else
format.html { render action: 'new' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #post.update(post_params)
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
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
private
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:name, :location_id)
end
end
Creating Post with location in Post _form.html.erb
<%= simple_form_for #post do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved: </h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :name %>
<%= f.select :location_id, Location.all.at_depth(4) { |l| [ l.name, l.id ] } %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
My question are
First question- f.select :location_id , how display location name, not location id, i am using with simple form
Second question- Post index got error in <%= post.location.name %>
<% #posts.each do |post| %>
<tr>
<td><%= post.name %></td>
<td><%= post.location.name %></td>
<td><%= link_to 'Show', post %></td>
<td><%= link_to 'Edit', edit_post_path(post) %></td>
<td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %> </td>
</tr>
<% end %>
First question:
Check the simple_form syntax for a dropdown. It is mentioned in the docs and you should be able to get this working by yourself.
Second question:
Does the offending post really have a related location? If it does not have one, it can not display the name of course. To counter these nil errors, use try:
<%= post.location.try(:name) %>
try will call the method name on location only if location is not nil.
For your first question :
Maybe you should read about "options_for_select"
http://guides.rubyonrails.org/form_helpers.html#option-tags-from-a-collection-of-arbitrary-objects
<% cities_array = City.all.map { |city| [city.name, city.id] } %>
<%= options_for_select(cities_array) %>
For your second question:
What is your error ?
Maybe one of your "post.location" is nil.
If so, try:
post.location.name unless post.location.nil?
Hope this can help
Related
I have a list of movie categories displayed on my home page. Along with this, I have displayed the list of ALL the movies currently available in the db. When the user clicks on one of the categories, I would like to re-render the containing the list of ALL movies to show ONLY the list of movies that belong to the category that the user selected.
I use link_to to display the list of categories. The link_to would be routed to a controller function which loads the movies that belong Only to the category selected by the user. Then a js.erb would be invoked with this generated list which would in-turn invoke a Rails partial.
The Rails partial would re-render the complete movie list to display ONLY the movies that belong to the selected category. The javascript and partial are getting invoked all right but the partial fails to re-render the list. Am not sure what I'm missing here.
app/views/movies/index.html.erb
<% #categories.each do |category| %>
<tr><td>
<%= link_to category, show_category_url(:genre => category), :remote => true %> <%end%>
<%if false %>
<%= link_to show_category_url, :remote => true do %>
category
<%end %>
</td></tr>
<% end %>
<div id="#movies_list">
<% #movies.each do |movie| %>
<tr>
<td><%= movie.title %></td>
<td><%= movie.category %> </td>
<td><%= movie.rating %></td>
<% if !current_user.nil? %>
<% if movie.user.email == current_user.email %>
<td><%= link_to 'Show', movie, :class => "btn btn-primary"%></td>
<td><%= link_to 'Edit', edit_movie_path(movie), :class => "btn btn-primary" %></td>
<td><%= link_to 'Destroy', movie, method: :delete, data: { confirm: 'Are you sure?' }, :class => "btn btn-primary" %></td>
<% end %>
<% end %>
</tr>
<% end %>
</div>
app/views/movies/show.js.erb
$("#movies_list").html("<%= escape_javascript(render("show_category")) %>");
app/views/movies/_show_categories.html.erb
<% #movies_in_category.each do |movie| %>
<tr>
<td><%= movie.title %></td>
<td><%= movie.rating %></td>
<% puts "************** movies/show_category"%>
<% puts movie.title %>
<% if false %>
<td>
<%= form_for #rating do |rating_form| %>
<%= rating_form.number_field :rating, class: 'rating', 'data-size' => 'xs'%>
<%= rating_form.submit 'Add', class: 'btn btn-primary btn-success' %>
<% end %>
</td>
<% end %>
<% if !current_user.nil? %>
<% if movie.user.email == current_user.email %>
<td><%= link_to 'Show', movie, :class => "btn btn-primary"%></td>
<td><%= link_to 'Edit', edit_movie_path(movie), :class => "btn btn-primary" %></td>
<td><%= link_to 'Destroy', movie, method: :delete, data: { confirm: 'Are you sure?' }, :class => "btn btn-primary" %></td>
<% end %>
<% end %>
</tr>
<% end%>
My partial is getting invoked all right but the re-rendering of div movies_list does not happen.
This is my controller code:
class MoviesController < ApplicationController
before_action :set_movie, only: [:show, :edit, :update, :destroy]
#before_action :authenticate_user!
# GET /movies
# GET /movies.json
def index
#movies = Movie.all
$all_movies = #movies
#categories = #movies.uniq.pluck(:category)
#movies_by_category = Hash.new
#categories.each do |category|
#movies_by_category[category] = Movie.where(:category => category).length
end
end
# GET /movies/1
# GET /movies/1.json
def show
respond_to do |format|
format.js {render layout: false}
puts "############## moviescontroller/show_category"
end
end
# GET /movies/new
def new
#movie = current_user.movies.new
end
# GET /movies/1/edit
def edit
end
# POST /movies
# POST /movies.json
def create
#movie = current_user.movies.new(movie_params)
respond_to do |format|
if #movie.save
format.html { redirect_to #movie, notice: 'Movie was successfully created.' }
format.json { render :show, status: :created, location: #movie }
else
format.html { render :new }
format.json { render json: #movie.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /movies/1
# PATCH/PUT /movies/1.json
def update
respond_to do |format|
if #movie.update(movie_params)
format.html { redirect_to #movie, notice: 'Movie was successfully updated.' }
format.json { render :show, status: :ok, location: #movie }
else
format.html { render :edit }
format.json { render json: #movie.errors, status: :unprocessable_entity }
end
end
end
# DELETE /movies/1
# DELETE /movies/1.json
def destroy
#movie.destroy
respond_to do |format|
format.html { redirect_to movies_url, notice: 'Movie was successfully destroyed.' }
format.json { head :no_content }
end
end
def show_category
category_selected = params[:genre]
#all_movies = Movie.all
#movies_in_category = Movie.where(category: category_selected)
puts "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
puts category_selected
puts #movies_in_category.length
end
def login
end
private
# Use callbacks to share common setup or constraints between actions.
def set_movie
#movie = Movie.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def movie_params
params.require(:movie).permit(:title, :category, :rating)
end
end
The reason is,
<div id="#movies_list">
contents goes here..
</div>
You shouldn't add # when defining id attribute for an element, That will be used when selecting an HTML element based on the selector. So remove #
<div id="movies_list">
contents goes here..
</div>
Hello I have a nested database "processing" which belongst to "shopping_process". However I want somehow to see the messages, which are saved in processing. How can I do that? If I go to http://localhost:3000/processings/index the Error: Couldn't find Processing with 'id'=index appears. Has somebody an idea?
processings_controller.rb
class ProcessingsController < ApplicationController
before_action :set_processing, only: [:show, :edit, :update, :destroy]
# GET /processings
# GET /processings.json
def index
#processings = Processing.all
end
# GET /processings/1
# GET /processings/1.json
def show
end
# GET /processings/new
def new
#processing = Processing.new
end
# GET /processings/1/edit
def edit
end
# POST /processings
# POST /processings.json
def create
#processing = Processing.new(processing_params)
respond_to do |format|
if #processing.save
format.html { redirect_to #processing, notice: 'Processing was successfully created.' }
format.json { render :show, status: :created, location: #processing }
else
format.html { render :new }
format.json { render json: #processing.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /processings/1
# PATCH/PUT /processings/1.json
def update
respond_to do |format|
if #processing.update(processing_params)
format.html { redirect_to #processing, notice: 'Processing was successfully updated.' }
format.json { render :show, status: :ok, location: #processing }
else
format.html { render :edit }
format.json { render json: #processing.errors, status: :unprocessable_entity }
end
end
end
# DELETE /processings/1
# DELETE /processings/1.json
def destroy
#processing.destroy
respond_to do |format|
format.html { redirect_to processings_url, notice: 'Processing was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_processing
#processing = Processing.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def processing_params
params.require(:processing).permit(:shopping_process_id, :shopping_list_id, :accepted, :responded, :message)
end
end
view/processings/index.html.erb
<p id="notice"><%= notice %></p>
<h1>Processings</h1>
<table>
<thead>
<tr>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #Processing.all.each do |processing| %>
<tr>
<td><%= link_to 'Show', processing %></td>
<td><%= link_to 'Edit', edit_processing_path(processing) %></td>
<td><%= link_to 'Destroy', processing, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Processing', new_processing_path %>
models/processing.rb
class Processing < ApplicationRecord
# db associations
belongs_to :shopping_process
belongs_to :shopping_list
# validations
validates :shopping_list, :presence => true
end
Now here comes the code for the database "shopping_processes"
shopping_processes_controller.rb
class ShoppingProcessesController < ApplicationController
load_and_authorize_resource
layout 'shopping_process', only: [:shopper_show, :senior_show]
# GET /shopping_processes/1
# GET /shopping_processes/1.json
def show
end
# POST /shopping_processes
# POST /shopping_processes.json
def create
#shopping_process.status =nil
#shopping_process.processed = nil
puts params.inspect
respond_to do |format|
if #shopping_process.save
format.html { redirect_to #shopping_process, notice: 'Shopping process was successfully created.' }
format.json { render :show, status: :created, location: #shopping_process }
else
format.html { render :new }
format.json { render json: #shopping_process.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /shopping_processes/1
# PATCH/PUT /shopping_processes/1.json
def update
respond_to do |format|
if #shopping_process.update(shopping_process_params)
format.html { redirect_to #shopping_process, notice: 'Shopping process was successfully updated.' }
format.json { render :show, status: :ok, location: #shopping_process }
else
format.html { render :edit }
format.json { render json: #shopping_process.errors, status: :unprocessable_entity }
end
end
end
# DELETE /shopping_processes/1
# DELETE /shopping_processes/1.json
def destroy
#shopping_process.destroy
respond_to do |format|
format.html { redirect_to shopping_processes_url, notice: 'Shopping process was successfully destroyed.' }
format.json { head :no_content }
end
end
def shopper_show
#shopping_process = ShoppingProcess.find(params[:id])
#users = {}
first = true
#shopping_process.shopping_lists.each do |shopping_list|
user = shopping_list.user
#users[user.id] = {color: (first ? 'blue' : 'yellow'), name: user.firstname + ' ' + user.lastname}
first = false
end
end
def senior_show
#shopping_process = ShoppingProcess.find(params[:id])
#shopping_process.shopping_lists.each do |shopping_list|
#if shopping_list.user == current_user
# #shopping_list = shopping_list
#end
#shopping_list = shopping_list
#to show the correct shopping list uncomment the block above and remove the declartion underneath it
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_shopping_process
#shopping_process = ShoppingProcess.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def shopping_process_params
params.require(:shopping_process).permit(:user_id, :status, :appointed, :processed, :shopping_list_id, processings_attributes: [ :shopping_list_id, :message ])
end
end
views/shopping_processes/form.html.erb
<%= form_for(shopping_process) do |f| %>
<% if shopping_process.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(shopping_process.errors.count, "error") %> prohibited this shopping_process from being saved:</h2>
<ul>
<% shopping_process.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :appointed %>
<%= f.datetime_select :appointed %>
</div>
<div class="field">
<%= f.label :shopper %>
<%= f.text_field :user_id, value: current_user.id, :readonly => true%>
</div>
<div class="field">
<%= f.label :shopping_list_id %>
<%= f.select :shopping_list_id, ShoppingList.accessible_by(current_ability).map{ |sl| [sl.name, sl.id] } %>
</div>
<!-- SUB FORM FOR NESTED RESOURCE : PROCESSINGS -->
<%= f.fields_for :processings, #shopping_process.processings.build do |ff| %>
<div>
<%= ff.label :Begleiter %>
<%= ff.select :shopping_list_id, ShoppingList.all.map{ |sl| [sl.user.firstname, sl.id]} , {:prompt => true} %>
</div>
<div>
<%= ff.label :message %>
<%= ff.text_field :message%>
</div>
<% end %>
<!-- Submit-->
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I have this code below which loads the patient data and with each one the update button updates it but on clicking nothing happens, here is the code:
<% emergency_case.patients.each do |patient| %>
<tr>
<%= simple_form_for (:patient),url: patients_edit_path(patient.id) do |f|%>
<td><%=f.input :name ,:input_html => { :value => patient.name},label: false %></td>
<td><%=f.input :IDNumber ,:input_html => { :value => patient.IDNumber},label: false %></td>
<td><%=f.input :age ,:input_html => { :value => patient.age},label: false %></td>
<td><%=f.input :phone ,:input_html => { :value => patient.phone},label: false %></td>
<td><%=f.input :address ,:input_html => { :value => patient.address},label: false %></td>
<td><%=f.input :injury ,:input_html => { :value => patient.injury},label: false %></td>
<td><%= f.collection_select(:state_id, State.all, :id, :state) %></td>
<td><%= f.collection_select(:Act, Act.all, :id, :act) %></td>
<td><%=f.submit %></td>
<% end %>
</tr>
<% end %>
Here is the paitent controller which am sending the form for to make updates on the paitent that is sent:
class PatientsController < ApplicationController
before_action :set_patient, only: [:show, :edit, :update, :destroy]
# GET /patients
# GET /patients.json
def index
#patients = Patient.all
end
# GET /patients/1
# GET /patients/1.json
def show
end
# GET /patients/new
def new
#patient = Patient.new
end
# GET /patients/1/edit
def edit
#patient =Patient.find(params[:id])
end
# POST /patients
# POST /patients.json
def create
#patient = Patient.new(patient_params)
respond_to do |format|
if #patient.save
format.html { redirect_to #patient, notice: 'Patient was successfully created.' }
format.json { render :show, status: :created, location: #patient }
else
format.html { render :new }
format.json { render json: #patient.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /patients/1
# PATCH/PUT /patients/1.json
def update
respond_to do |format|
if #patient.update(patient_params)
format.html { redirect_to #patient, notice: 'Patient was successfully updated.' }
format.json { render :show, status: :ok, location: #patient }
else
format.html { render :edit }
format.json { render json: #patient.errors, status: :unprocessable_entity }
end
end
end
# DELETE /patients/1
# DELETE /patients/1.json
def destroy
#patient.destroy
respond_to do |format|
format.html { redirect_to patients_url, notice: 'Patient was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_patient
#patient = Patient.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def patient_params
params.require(:patient).permit(:name, :isDead, :status, :IDNumber, :emergency_case_id,:state_id,:address,:age,:phone,:injury,:act)
end
end
Several issues to contend with here:
<% emergency_case.patients.each do |patient| %>
<%= content_tag :tr do %>
<%= simple_form_for patient, method: :put do |f|%>
<% attributes = %i(name IDNumber age phone address injury) %>
<% patient.attributes do |attr| %>
<%= content_tag :td, f.input attr, input_html: { value: patient.send(attr)}, label: false %>
<% end %>
<%= content_tag :td, f.state_select :state_id %>
<%= content_tag :td, f.collection_select(:Act, Act.all, :id, :act) %>
<%= content_tag :td, f.submit %>
<% end %>
<% end %>
<% end %>
ALWAYS use snake_case for attributes (IDNumber is baaad umkay)
Check out the state_select gem
Loops are the BEST way to keep forms succinct & efficient
Your form is sending to the edit action -- you need to send to the update action
#4 will answer your question -- patients_edit_path(patient.id)
What you need is to send to the update path: patient_path(patient), method: :put... or simply: patient, method: :put
let simple form do the work for you on the url, method, etc unless you have something that is custom. If this doesn't work please post more info on the error you are getting in your post.
<% emergency_case.patients.each do |patient| %>
<tr>
<%= simple_form_for patient do |f|%>
....#form stuff
<td><%=f.submit %></td>
<% end %>
</tr>
<% end %>
I have a model called Images with an uploader attached to it (Carrierwave). Images belongs to a model called Listing. After creating a listings I'm redirected to the Images index page to upload files (localhost:3000/listings/1/images)
But for some reason every time I create a listing an image it's created at the same time. There's actually no image present but it displays the "delete" link I have for each image.
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
Any help? Thanks.
Listings Controller
class ListingsController < ApplicationController
before_action :set_listing, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :except => [:show, :index]
def index
#listings = Listing.order('created_at DESC')
respond_to do |format|
format.html
format.json { render json: #listings }
end
end
def show
end
def new
#listing = Listing.new
#listing.user = current_user
end
def edit
end
def create
#listing = Listing.new(listing_params)
#listing.user = current_user
respond_to do |format|
if #listing.save
format.html { redirect_to listing_images_path(#listing), notice: 'Post was successfully created.' }
else
format.html { render action: 'new' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #listing.update(listing_params)
flash[:notice] = 'Deal was successfully updated.'
format.html { redirect_to #listing }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #listing.errors, status: :unprocessable_entity }
end
end
end
def destroy
#listing.destroy
respond_to do |format|
format.html { redirect_to listings_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_listing
#listing = Listing.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def listing_params
params.require(:listing).permit(:id, :condition, :description, :nickname, :price, :size, :title, :user_id)
end
end
Listings Form
<%= form_for(#listing, :html => { :class => 'form', :multipart => true }) do |f| %>
<% if #listing.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#listing.errors.count, "error") %> prohibited this listing from being saved:</h2>
<ul>
<% #listing.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div>
<%= f.label :title %>
<%= f.text_field :title, :required => true %>
</div>
<div>
<%= f.label :price %>
<%= f.text_field :price %>
</div>
<div class="actions">
<%= f.submit 'Submit', :class => 'buyNow' %>
</div>
<% end %>
Images Controller
class ImagesController < ApplicationController
before_action :set_image, only: [:show, :edit, :update, :destroy]
before_filter :load_listing
def index
#images = #listing.images.load
#image = #listing.images.new
end
def new
end
def edit
end
def create
#image = #listing.images.new(image_params)
respond_to do |format|
if #image.save
format.html { redirect_to :back, notice: 'Image was successfully created.' }
format.json { head :no_content }
else
format.html { render action: 'new' }
format.json { render json: #image.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #image.update(image_params)
format.html { redirect_to (#image.listing), notice: 'Image was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #image.errors, status: :unprocessable_entity }
end
end
end
def destroy
#image = #listing.images.find(params[:id])
#image.destroy
respond_to do |format|
format.html { redirect_to :back }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_image
#image = Image.find(params[:id])
end
def load_listing
#listing = Listing.find(params[:listing_id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def image_params
params.require(:image).permit(:file, :listing_id)
end
end
Images Index
<div>
<%= form_for [#listing, #image], :html => { :class => 'uploadImages', :multipart => true } do |f| %>
<%= f.hidden_field :listing_id %>
<div>
<%= f.label :file, 'Upload Images' %>
<%= f.file_field :file, multiple: true, name: 'image[file]' %>
</div>
<% end %>
</div>
<div id="progress"></div>
<% if #images.present? %>
<ul class="editGallery">
<% #listing.images.each do |image| %>
<li>
<%= image_tag image.file_url(:list) if image.file? %>
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
</li>
<% end %>
</ul>
<% end %>
The problem is this line:
#image = #listing.images.new
That's building a new image for #listing, so when you call #listing.images.each that new image is included in the images array. Check that the image has actually been saved to the database before constructing a delete link for it.
<% #listing.images.each do |image| %>
<% unless image.new_record? %>
<li>
<%= image_tag image.file_url(:list) if image.file? %>
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
</li>
<% end %>
<% end %>
Take a look at this part of your code:
<% if #images.present? %>
<ul class="editGallery">
<% #listing.images.each do |image| %>
<li>
<%= image_tag image.file_url(:list) if image.file? %>
<span><%= link_to 'DELETE', listing_image_path(#listing, image.id), data: { confirm: 'Are you sure?' }, :method => :delete, :class => 'delete' %></span>
</li>
<% end %>
</ul>
I believe your problem is a combination of this and your images controller index action.
When you hit the index action you create a new record #image = #listing.images.new
Now your #listing.images.each call registers on the object that hasn't been saved.
My Rails application have two model. Location and Post, Location have many post.I am Using
ancestry gem.
class Post < ActiveRecord::Base
belongs_to :location, :counter_cache => true
end
class Location < ActiveRecord::Base
include Tree
has_ancestry :cache_depth => true
has_many :posts
end
My Post Controller
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
#posts = Post.all
end
def show
end
def new
#post = Post.new
end
def edit
end
def create
#post = Post.new(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: #post }
else
format.html { render action: 'new' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #post.update(post_params)
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
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:name)
end
end
If i am create new Post with which Location belongs in _form.html.erb
<%= form_for(#post) do |f| %>
<% if #post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#post.errors.count, "error") %> prohibited this post from being saved: </h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= select :location_id, Location.all.at_depth(4) { |l| [ l.name, l.id ] } %>
<div class="actions">
<%= f.submit %>
</div>
Browser show error message which is display bellow
ArgumentError in Posts#new
Not sure if this fixes your error, but:
To make the dropdown working, change the select line to:
<%= f.select :location_id, Location.all.at_depth(4) { |l| [ l.name, l.id ] } %>
This is because you want the formbuilder f to handle the creation of the form element.
You also have to whitelist the :location_id parameter in the controller:
def post_params
params.require(:post).permit(:name, :location_id)
end