Ruby on Rails - Render partial from another controller - html

I'm new to rails and I've looked around and none of the solutions on here I've found seem to work. I feel that I am missing something crucial.
I am trying to render a partial from /views/names/_form.html.erb into another file with a different controller /views/posts/index.html.erb. I keep getting the following error.
app/views/names/_form.html.erb where line #1 raised:
First argument in form cannot contain nil or be empty
Extracted source (around line #1):
<%= form_for(#name) do |f| %>
<% if #name.errors.any? %>
<%= pluralize(#name.errors.count, "error") %> prohibited this >name from being saved:
My HTML code is as follows:
<div class="modal" id="myModal">
<h1>Company Name</h1>
<div class="modal-body">
<%= render :partial => '/names/form' %>
...etc...
My Names controller is as follows:
class NamesController < ApplicationController
before_action :set_name, only: [:show, :edit, :update, :destroy]
def index
#names = Name.all
end
def show
end
def new
#name = Name.new
end
def edit
end
def create
#name = Name.new(name_params)
respond_to do |format|
if #name.save
format.html { rredirect_to #name, notice: 'Post created' }
format.json { render :show, status: :created, location: #name }
else
format.html { render :new }
format.json { render json: #name.errors, status: :unprocessable_entity }
end
end
end
My Posts controller is as follows:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index]
# before_filter :first_time_visiting?
# GET /posts
# GET /posts.json
def index
#posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
#posts = Post.all
end
# GET /posts/new
def new
#post = current_user.posts.build
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
#post = current_user.posts.build(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
And finally this is my routes file
Rails.application.routes.draw do
resources :posts
devise_for :users
resources :names
root 'index#home'
get "about" => 'index#about'
get "contact" => 'index#contact'
get 'closings' => 'index#closings'
get 'signin' => 'users#sign_in'
Thank you so much for your help.

Add the following line in your post/index method. when to render the partial in your view html , your form try to find the #name object which not found in the post/index method . So we need to initialise #name with new Name object.
def index
#posts = Post.all
#name = Name.new
end

Related

How do you get an image stored in a SQL Database and display it in a carosel? (Ruby on rails)

Ive been trying to wrap my head around this and find a solution but I feel like Ive hit a stump. Im trying to grab the first, second, or third photo from my SQL database and feed it into my bootstrap carousel on my homepage. This is my code for my photos controller:
class PhotosController < ApplicationController
before_action :set_photo, only: [:show, :edit, :update, :destroy]
# GET /photos
# GET /photos.json
def index
#photos = Photo.all
end
# GET /photos/1
# GET /photos/1.json
def show
end
def show_first
#photos = Photo.find(1)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_second
#photos = Photo.find(2)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_third
#photos = Photo.find(3)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_image
#photos = Photo.find(params[:id])
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
# GET /photos/new
def new
#photo = Photo.new
end
# GET /photos/1/edit
def edit
end
# POST /photos
# POST /photos.json
def create
#photo = Photo.new(photo_params)
respond_to do |format|
if #photo.save
format.html { redirect_to #photo, notice: 'Photo was successfully created.' }
format.json { render :show, status: :created, location: #photo }
else
format.html { render :new }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /photos/1
# PATCH/PUT /photos/1.json
def update
respond_to do |format|
if #photo.update(photo_params)
format.html { redirect_to #photo, notice: 'Photo was successfully updated.' }
format.json { render :show, status: :ok, location: #photo }
else
format.html { render :edit }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /photos/1
# DELETE /photos/1.json
def destroy
#photo.destroy
respond_to do |format|
format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_photo
#photo = Photo.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def photo_params
params.require(:photo).permit(:title, :medium, :description, :file)
end
end
Ive been looking up and trying to find a good and simple way to accomplish this. And have tried to use the methods like show_first, second, etc. But Im not sure if I am even implementing it right. Would any be able to shed some light on this or at least point me in the right direction? Is the image/* right? Im basically doing my learning on my own and any help and thorough explanation would be awesome and greatly appreciated!
Why not just do it in the show action?
# GET photos/:id
# GET photos/:id.jpg
def show
#photo = Photo.find(params[:id])
respond_to do |format|
format.html {}
format.jpg do
send_data #photos.image, type: 'image/jpeg', disposition: 'inline'
end
end
end
You can then display the photos by:
<% Photo.order(created_at: :desc).limit(10).each do |photo| %>
<%= tag :img, src: path_for(photo, format: :jpg) %>
<% end %>

Couldn't find Tag while searching a product with tags in rails

i have multiple tags for each product in my rails project and i wanted to search my products through tags and i've been getting the following error when i search:
ActiveRecord::RecordNotFound in ProductsController#index
Couldn't find Tag
I have used a tags model to store the tags and a taggings model to connect tags and products table(with many to many relationship)
PRODUCTS_CONTROLLER
class ProductsController < ApplicationController
# before_action :authenticate_user!
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
if params[:tag]
#products = Product.tagged_with(params[:tag])
else
#products = Product.all
end
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
#product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
#product = current_user.products.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_product
#product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:filetype, :title, :img_url, :description, :all_tags, :price, :uploaded_by, :tutorial_url)
end
end
PRODUCT MODEL
class Product < ActiveRecord::Base
belongs_to :user
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
has_many :comments, dependent: :destroy
has_attached_file :img_url, styles: { large: "800x600>", medium: "320x200>", thumb: "100x80#" }, validate_media_type: false
validates_attachment_content_type :img_url, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
def self.tagged_with(name)
Tag.find_by!(name: name).products
end
def all_tags=(names)
# names="music, spotify"
self.tags = names.split(',').map do |name|
Tag.where(name: name).first_or_create!
end
end
def all_tags
tags.map(&:name).join(", ")
end
end
TAG MODEL
class Tag < ActiveRecord::Base
has_many :taggings, dependent: :destroy
has_many :products, through: :taggings
end
TAGGINGS MODEL
class Tagging < ActiveRecord::Base
belongs_to :product
belongs_to :tag
end
and this is how i m searching the tags
<div id="search-bar">
<%= form_tag products_path, :action=>"index", :method=>"get" do %>
<%= text_field_tag :tag, params[:tag], :name=>"tag", :placeholder=>" Search Anything", :id=>"s-bar" %>
<%= submit_tag "Search",:name=>"tag", :value=>"search", :style=>"width: 100px; border: none; background: #eee; font-size: 25px; position: relative; top: 5px; display: none;"%>
<%end%>
</div>
In your product model,
def self.tagged_with(name)
tags = Tag.where('LOWER(name) like ?', "#{name.downcase}")
products = []
tags.each do |tag|
products << tag.products
end
return products
end
This will return an array of products whose tags are similar to the one searched in your text box.

Unable to upload whole csv file data into rails 4.2 with sqlite3 database

My csv file takes upto 26 OR 78 values from the large file and don't import the whole data.
rails console view
irb(main):009:0> Stocking.count
(0.0ms) SELECT COUNT(*) FROM "stockings"
=> 26
irb(main):010:0> Stocking.delete_all
SQL (109.4ms) DELETE FROM "stockings"
=> 26
irb(main):011:0> Stocking.count
(0.0ms) SELECT COUNT(*) FROM "stockings"
=> 78
irb(main):012:0> Stocking.delete_all
SQL (62.5ms) DELETE FROM "stockings"
=> 78
irb(main):013:0> Stocking.count
(0.0ms) SELECT COUNT(*) FROM "stockings"
=> 26
As I checked through the rails console with count command.
index.html.erb
<h2>Import Stock File</h2>
<%= form_tag import_stockings_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
stockings_controller.rb
class StockingsController < ApplicationController
before_action :set_stocking, only: [:show, :edit, :update, :destroy]
# GET /Stockings
# GET /deldetails.json
def index
#stockings = Stocking.all
end
def import
Stocking.import(params[:file])
redirect_to stockings_url, notice: "Stockings imported."
end
# GET /Stockings/1
# GET /Stockings/1.json
def show
end
# GET /Stockings/new
def new
#stocking = Stocking.new
end
# GET /stockings/1/edit
def edit
end
# POST /Stockings
# POST /Stockings.json
def create
#stocking = Stocking.new(stocking_params)
respond_to do |format|
if #stocking.save
format.html { redirect_to #stocking, notice: 'Stocking was successfully created.' }
format.json { render :show, status: :created, location: #stocking }
else
format.html { render :new }
format.json { render json: #stocking.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /Stockings/1
# PATCH/PUT /stockings/1.json
def update
respond_to do |format|
if #stocking.update(stocking_params)
format.html { redirect_to #stocking, notice: 'Stocking was successfully updated.' }
format.json { render :show, status: :ok, location: #stocking }
else
format.html { render :edit }
format.json { render json: #stocking.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stockings/1
# DELETE /stockings/1.json
def destroy
#stocking.destroy
respond_to do |format|
format.html { redirect_to stockings_url, notice: 'Stocking was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_stocking
#stocking = Stocking.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def stocking_params
params.require(:stocking).permit(:season, :category, :articleno, :description, :color, :quantity, :rprice, :tamount, :cartonno )
end
end
stocking.rb
class Stocking < ActiveRecord::Base
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
puts row.inspect
end
end
end
application.rb
require File.expand_path('../boot', __FILE__)
require 'csv'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Stock
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
config.middleware.use 'Utf8Sanitizer'
end
end
routes.rb
Rails.application.routes.draw do
root 'stockings#index'
resources :stockings do
collection { post :import }
end
end
I would like to import all the data into my sqlite3 database.
Any suggestions are most welcome.
Thank you in advance.
The real problem was lying with my uploading file as it was not in correct format that is it was not normalized.

Posting JSON to Rails 4

I am having trouble posting to a JSON field (using postman) in my Ruby + Rails web app. I am confused as to what the controller permissions (strong params) need to be and the subsequent posting format.
I am trying to send in raw format using postman (Content-type is set to application/json)
{"recipe":{"recipe_id":"174a4839020d0820","Category":"Eaten"}, "Nuts":{...}, "Milk":{...}}
My controller looks like:
class OnboardingsController < ApplicationController
before_action :set_onboarding, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :if => Proc.new { |c| c.request.format == 'application/json' }
# GET /onboardings
# GET /onboardings.json
def index
#onboardings = Onboarding.all
end
# GET /onboardings/1
# GET /onboardings/1.json
def show
end
# GET /onboardings/new
def new
#onboarding = Onboarding.new
end
# GET /onboardings/1/edit
def edit
end
# POST /onboardings
# POST /onboardings.json
def create
ap params
#onboarding = Onboarding.new(onboarding_params)
respond_to do |format|
if #onboarding.save
format.html { render :json => #onboarding.to_json , notice: 'Onboarding was successfully created.' }
format.json { render :show, status: :created, location: #onboarding }
else
format.html { render :new }
format.json { render json: #onboarding.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /onboardings/1
# PATCH/PUT /onboardings/1.json
def update
respond_to do |format|
if #onboarding.update(onboarding_params)
format.html { redirect_to #onboarding, notice: 'Onboarding was successfully updated.' }
format.json { render :show, status: :ok, location: #onboarding }
else
format.html { render :edit }
format.json { render json: #onboarding.errors, status: :unprocessable_entity }
end
end
end
# DELETE /onboardings/1
# DELETE /onboardings/1.json
def destroy
#onboarding.destroy
respond_to do |format|
format.html { redirect_to onboardings_url, notice: 'Onboarding was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_onboarding
#onboarding = Onboarding.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def onboarding_params
params.require(:onboarding).permit(:recipe, :recipe_id, :category, `enter code here`:fruits, :nuts, :cereal, :milk)
end
end
And the response is all nulls but something gets created:
{
"id": 32,
"recipe": null,
"fruits": null,
"nuts": null,
"cereal": null,
"milk": null,
"created_at": "2014-09-29T06:11:39.874Z",
"updated_at": "2014-09-29T06:11:39.874Z"
}
The log looks like:
Unpermitted parameters: recipe
(0.2ms) BEGIN
SQL (0.6ms) INSERT INTO "onboardings" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", "2014-09-28 23:11:39.874650"], ["updated_at", "2014-09-28 23:11:39.874650"]]
(2.1ms) COMMIT
Rendered onboardings/show.json.jbuilder (0.4ms)
Completed 201 Created in 126ms (Views: 5.5ms | ActiveRecord: 9.6ms)
Any direction is appreciated! Totally lost after looking through all relevant SO posts.
The key of your POST data is recipe, but your onboarding_params is
params.require(:onboarding)
In order to do the strong params correctly I think that would need to be something like
params.require(:recipe).permit(:recipe_id, :Category)

How to parse the json data or (json code) from Ruby on rails

I have an Ruby on rails source,code now i want to parse the data, and send the data.In my code,it will fetches the name from user and display it,How to parse the data in ROR.
This is my controller.rb code
def index
#hotels = Hotel.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #hotels }
end
end
# GET /hotels/1
# GET /hotels/1.json
def show
#hotel = Hotel.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #hotel }
end
end
# GET /hotels/new
# GET /hotels/new.json
def new
#hotel = Hotel.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #hotel }
end
end
# GET /hotels/1/edit
def edit
#hotel = Hotel.find(params[:id])
end
# POST /hotels
# POST /hotels.json
def create
#hotel = Hotel.new(params[:hotel])
respond_to do |format|
if #hotel.save
format.html { redirect_to #hotel, notice: 'Hotel was successfully created.' }
format.json { render json: #hotel, status: :created, location: #hotel }
else
format.html { render action: "new" }
format.json { render json: #hotel.errors, status: :unprocessable_entity }
end
end
end
# PUT /hotels/1
# PUT /hotels/1.json
def update
#hotel = Hotel.find(params[:id])
respond_to do |format|
if #hotel.update_attributes(params[:hotel])
format.html { redirect_to #hotel, notice: 'Hotel was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #hotel.errors, status: :unprocessable_entity }
end
end
end
# DELETE /hotels/1
# DELETE /hotels/1.json
def destroy
#hotel = Hotel.find(params[:id])
#hotel.destroy
respond_to do |format|
format.html { redirect_to hotels_url }
format.json { head :no_content }
end
end
How to parse these data in ROR using Json
HOw to write parsing json file for these data,how to do that one
**Answer of my question**
This part we have to do in controller
hotelscontroller.erb
respond_to :json, :xml
def index
#hotels = Hotel.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: #hotels.to_json(:only => [ :id, :name ]) }
end
end
view/index.json.erb
[
<% #hotels.each do |hotel| %>
{ 'id': <%= hotel.id %>, 'name': "<%= hotel.name %>" },
<% end %>
]
routes.rb
get 'hotels' => 'hotels#index', :as => 'hotels'
There are many ways:
Create method to_json for each model
Create view named, i.e. hotels/index.json.erb and write JSON code using ERb templating engine
[
<% #hotels.each do |hotel| %>
{ 'id': <%= hotel.id %>, 'name': "<%= hotel.name %>" },
<% end %>
]
Use library like jbuilder (on the bottom of page is list of alternatives to JBuilder)
# hotels/index.json.jbuilder
json.array!(#hotels) do |hotel|
json.id hotel.id
json.name hotel.name
end
You can covert a hash to json by to_json method. For reference please see http://apidock.com/rails/ActiveRecord/Serialization/to_json
for example, if you want to write all hotels to external file.
file = File.open("hotels.txt", "w")
file.puts Hotel.all.to_json
file.close
this will write all hotels in external file hotels.txt