Added new field is not saved in mongodb in rails? - ruby-on-rails

grading.rb
class Grading
require 'autoinc'
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Autoinc
field :quantity, type: Float
field :count, :type => Float
field :grade_id, type: Integer
field :batch_id, type: Integer
field :variety_id, type: Integer
field :serial_id, :type => Integer
field :soaked, :type => Boolean
# Mongoid AutoInc
increments :serial_id
# Associations
belongs_to :grade
belongs_to :variety
belongs_to :batch
has_many :grading_weighments, :dependent=> :destroy
# validations
validates_presence_of :grade_id,:batch_id,:variety_id
validates_presence_of :quantity , numericality: {:greater_than => 0}
validates_presence_of :count ,numericality: {:greater_than_or_equal_to => 10, :less_than_or_equal_to => 150}
attr_accessor :weights
accepts_nested_attributes_for :grading_weighments, :allow_destroy => true
end
gradingcontroller.rb
class GradingsController < ApplicationController
before_action :set_grading, only: [:show, :edit, :update, :destroy]
# load_and_authorize_resource
# GET /gradings
# GET /gradings.json
def index
#gradings = Grading.all.order('date DESC')
#q = Batch.search(params[:q])
#batches = #q.result(:distinct => true).in(status:["HLQDone","GradingDone"]).order('updated_at ASC').page(params[:page]).per(5)
# #batches = Batch.all.order('created_at DESC').page(params[:page]).per(5) .where(status: "HLQ_Done")
#grades = Grade.all.map{|g| [g.id.to_s,g.name]}
#varieties = Variety.all.map{|v| [v.id.to_s,v.name]}
respond_to do |format|
format.js
format.html
end
end
# GET /gradings/1
# GET /gradings/1.json
def show
end
# GET /gradings/new
def new
#grading = Grading.new
end
# GET /gradings/1/edit
def edit
end
# POST /gradings
# POST /gradings.json
def create
#grades = Grade.all.map{|g| [g.id.to_s,g.name]}
#varieties = Variety.all.map{|v| [v.id.to_s,v.name]}
#grading = Grading.new(grading_params)
#batch= #grading.batch
weights=params[:grading][:weights]
#grading.quantity= weights.map! { |i| i.to_f }.sum
respond_to do |format|
if #grading.save
#grading_weighments=GradingWeighment.new
#grading_weighments.grading_id =#grading.id
#grading_weighments.weights =weights.join(',')
#grading_weighments.save
format.html { redirect_to gradings_path, notice: 'Grading was successfully created.' }
format.json { render action: 'show', status: :created, location: #grading }
format.js
else
format.html { render action: 'new' }
format.json { render json: #grading.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /gradings/1
# PATCH/PUT /gradings/1.json
def update
g=[]
puts "#{params[:grading][:grading_weighments_attributes]}"
params[:grading][:grading_weighments_attributes].each do |key,value|
g<<value[:weights]
end
puts "=============#{g}"
q= g.map{ |i| i.to_f }.sum
puts "==========aes==#{q}"
#grading.update_attributes(quantity: q)
#gw= GradingWeighment.find_or_create_by(grading_id: #grading.id)
#gw.update_attributes(weights: g.join(','))
respond_to do |format|
if #grading.update(grading_params)
#grades = Grade.all.map{|g| [g.id.to_s,g.name]}
#varieties = Variety.all.map{|v| [v.id.to_s,v.name]}
format.html { redirect_to gradings_path, notice: 'Grading was successfully updated.' }
format.json { respond_with_bip(#grading) }
format.js
else
format.html { render action: 'edit' }
format.json { render json: #grading.errors, status: :unprocessable_entity }
format.js
end
end
end
# DELETE /gradings/1
# DELETE /gradings/1.json
def destroy
#grading_id=#grading.id
batch_number= #grading.batch.batch_number
#grading.destroy
respond_to do |format|
#del_batch = Batch.find_by(batch_number: batch_number)
#length=#del_batch.gradings.length
#del_batch.update_attributes(status: "HLQ_Done") if #length==0
format.html { redirect_to gradings_url }
format.json { head :no_content }
format.js
end
end
def fetch_weights
#grading_weighments=GradingWeighment.find_by(grading_id: params[:id]).weights
#grading=Grading.find(params[:id])
(#grading.grading_weighments.first.weights.split(',').length-1).times {#grading.grading_weighments.build}
respond_to do |format|
format.html { render :nothing => true, :status => 200, :content_type => 'text/html'}
format.json { head :no_content }
format.js
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_grading
#grading = Grading.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def grading_params
params.require(:grading).permit(:quantity,:batch_id,:variety_id,:grade_id,:count, :weights,:grading_weighments_attributes, :soaked)
end
end
list.html.erb
<thead>
<tr>
<th>Count</th>
<th>Grade</th>
<th>Variety</th>
<th>Quantity</th>
<th>Soaked</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<%batch= #batch if !batch%>
<%if batch.gradings.length==0%>
<tr><td colspan="5" class="warning">Grading is not done for batch with number <%=batch.batch_number%></td></tr>
<%else%>
<%gradings=batch.gradings.order('created_at DESC')%>
<%gradings.each do |grading|%>
<tr id="<%=grading.id%>">
<td><%= best_in_place grading, :count, :as => :input, required:true%></td>
<td><%= best_in_place grading, :grade_id, :as => :select, :collection => #grades %></td>
<td><%= best_in_place grading, :variety_id, :as => :select, :collection => #varieties %></td>
<td><%= best_in_place grading, :quantity, :as => :input%></td>
<td><%= best_in_place grading, :soaked, :as => :input, required:true%></td>
<td>
<%= link_to "getweights/#{grading.id}", method: :get, :remote => true ,class:'btn btn-info' do%>
<i class="fa fa-plus"></i>
<% end %>
<%= link_to grading, method: :delete, remote:true,data: { confirm: 'Are you sure?' } ,title:'Delete this grading', class:'btn btn-danger' do%>
<i class="fa fa-trash-o"></i>
<%end%>
</td>
</tr>
<%end%>
<%end%>
</tbody>
</table>
new.grading.html.erb
<div class="form-group">
<%= f.label :soaked ,class:"sr-only"%>
<%= f.select :soaked ,options_for_select(["Soaked", "Un-soaked"]), {:include_blank => "Select Soaking"}, class: "form-control" , autocomplete:"off", required: true %>
</div>
Here i am added new field called as "field :soaked, :type => Boolean", this field is not saved in database and not showing in views. How can solve this problem please help me.
Note: I passed grading params (soaked) also.

Try this:
<%= f.select :active, [['Soaked', true], ['Un-soaked', false]] %>

soaked will only accept TRUE or FALSE, while you are trying to save "Soaked", "Un-soaked"
<%= f.check_box :soaked %>
You can use CHECKBOX.
If you still want to use "Soaked" and "Un-soaked". You can apply check in your controller. If Soaked is selected then save TRUE else FALSE
Try This One
<%= f.select :soaked, options_for_select([['Soaked', true], ['Un-soaked', false]]) %>

Related

Cocoon link_to_remove_association remove only for view but not in the database

link_to_remove_association works for view but doesn't not delete in the database. Not sure what's wrong in my code. I can add and update totally fine.
Parameters:
"todo_list" => {
"name" => "Stuff to do",
"todo_tasks_attributes" => {
"0" => {
"_destroy" => "1",
"name" => "1",
"completed" => "0",
"due" => "",
"id"=>"3"
},
"1" => {
"_destroy" => "false",
"name" => "2",
"completed" => "0",
"due" => "",
"id" => "4"
},
"2" => {
"_destroy" => "false",
"name" => "3",
"completed" => "1",
"due" => "",
"id" => "5"
},
"3" => {
"_destroy" => "false",
"name"=>"4",
"completed" => "0",
"due" => "",
"id" => "6"
}
}
},
"commit" => "Update Todo list", "id" => "2" }
In my log I get:
Unpermitted parameter: :_destroy
Unpermitted parameter: :_destroy
Unpermitted parameter: :_destroy
Unpermitted parameter: :_destroy
This is my TodoList controller
class TodoListsController < ApplicationController
before_action :set_todo_list, only: [:show, :edit, :update, :destroy]
# GET /todo_lists
# GET /todo_lists.json
def index
#todo_lists = TodoList.all
end
# GET /todo_lists/1
# GET /todo_lists/1.json
def show
end
# GET /todo_lists/new
def new
#todo_list = TodoList.new
end
# GET /todo_lists/1/edit
def edit
end
# POST /todo_lists
# POST /todo_lists.json
def create
#todo_list = TodoList.new(todo_list_params)
respond_to do |format|
if #todo_list.save
format.html { redirect_to #todo_list, notice: 'Todo list was successfully created.' }
format.json { render :show, status: :created, location: #todo_list }
else
format.html { render :new }
format.json { render json: #todo_list.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /todo_lists/1
# PATCH/PUT /todo_lists/1.json
def update
if #todo_list.update(todo_list_params)
redirect_to edit_todo_list_path(#todo_list), notice: 'Todo list was successfully updated.'
else
render :edit
end
end
# DELETE /todo_lists/1
# DELETE /todo_lists/1.json
def destroy
#todo_list.destroy
respond_to do |format|
format.html { redirect_to todo_lists_url, notice: 'Todo list was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_todo_list
#todo_list = TodoList.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def todo_list_params
# params.require(:todo_list).permit(:name, todo_tasks_attributes: [:id, :_destory, :todo_list_id, :name, :completed, :due])
params
.require(:todo_list)
.permit(:name, todo_tasks_attributes: TodoTask.attribute_names.map(&:to_sym).push(:_destory))
end
end
TodoList model
class TodoList < ApplicationRecord
has_many :todo_tasks, dependent: :destroy
accepts_nested_attributes_for :todo_tasks,
allow_destroy: true,
reject_if: proc { |att| att['name'].blank? }
end
todotask model
class TodoTask < ApplicationRecord
belongs_to :todo_list, optional: true
end
_form
<%= simple_form_for(#todo_list) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
</div>
<table class='table'>
<thead>
<tr>
<th></th>
<th>Task Name</th>
<th>Completed</th>
<th>Due</th>
</tr>
</thead>
<tbody class='todo_tasks'>
<%= f.simple_fields_for :todo_tasks do |builder| %>
<%= render 'todo_task_fields', f: builder %>
<% end %>
</tbody>
</table>
<div class="form-actions">
<%= f.button :submit %>
<div class="links">
<%= link_to_add_association('Add Task', f, :todo_tasks, class: 'btn btn-primary', data: { association_insertion_node: '.todo_tasks', association_insertion_method: :append } ) %>
</div>
</div>
_todo_task_fields
<tr class="nested-fields">
<td>
<%= link_to_remove_association "remove task", f, class: 'btn btn-default btn-xs' %>
</td>
<td><%= f.input :name, label: false %></td>
<td><%= f.input :completed, label: false %></td>
<td><%= f.input :due, label: false, as: :string %></td>
</tr>
Sily me... I had a spelling mistake on my params
:_destory -> :_destroy.
Problem solved

Nested form(cocoon gem) inside a table in rails

I'm busy with a invoicing application and i'm trying to put a nested form from the cocoon gem inside a <tbody></tbody>. The nested form is working perfectly but it doesn't show up in the <tbody></tbody> but at some random place above the table head. I think it's because you can't have <div class=nested-fields></div> inside the table body but i'm not sure how to do it differently.
i have this in my invoices/_form.html.erb :
<%= form_for #invoice do |f| %>
<% if #invoice.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#invoice.errors.count, "error") %> prohibited this invoice from being saved:</h2>
<ul>
<% #invoice.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="row">
<div class="col-sm-12">
<table class="table table-striped">
<thead>
<tr>
<th class="hidden-480"> Hoeveelheid </th>
<th class="hidden-480"> Beschrijving </th>
<th class="hidden-480"> Bedrag </th>
<th class="hidden-480"> Totaal </th>
<th class="hidden-480"> Btw(%) </th>
</tr>
</thead>
<tbody>
<%= f.fields_for :products do |product| %>
<%= render 'product_fields', f: product %>
<%= link_to_add_association 'Item toevoegen', f, :products, class: 'btn btn-primary btn-success' %>
<% end %>
</tbody>
</table>
</div>
</div>
<% end %>
invoices/_product_fields.html.erb
<div class="nested-fields">
<tr>
<td> <%= f.text_field :quantity %> </td>
<td> <%= f.text_area :description %> </td>
<td> <%= f.number_field :unitprice %> </td>
<td> €200 </td>
<td> <%= f.select(:btw, [[' 21%', 21, title: '21%'],[' 6%', 6, title: '6%'], [' 0%', 0, title: '0%']]) %> </td>
</tr>
<%= link_to_remove_association 'x', f, class: 'btn btn-primary btn-danger' %>
</div>
Invoice.rb - model
class Invoice < ActiveRecord::Base
has_one :company
has_one :customer
has_many :products
accepts_nested_attributes_for :customer, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true
validates :number, :currency, :date, :duedate, :btwtotal, :subtotal, :total, presence: true
end
Product.rb - model
class Product < ActiveRecord::Base
belongs_to :invoice
end
Invoices_controller.rb
class InvoicesController < ApplicationController
before_action :set_invoice, only: [:show, :edit, :update, :destroy]
# GET /invoices
# GET /invoices.json
def index
#invoices = Invoice.all
end
# GET /invoices/1
# GET /invoices/1.json
def show
end
# GET /invoices/new
def new
#invoice = Invoice.new
#invoice.products.build
end
# GET /invoices/1/edit
def edit
end
# POST /invoices
# POST /invoices.json
def create
#invoice = Invoice.new(invoice_params)
respond_to do |format|
if #invoice.save
format.html { redirect_to #invoice, notice: 'Invoice was successfully created.' }
format.json { render :show, status: :created, location: #invoice }
else
format.html { render :new }
format.json { render json: #invoice.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /invoices/1
# PATCH/PUT /invoices/1.json
def update
respond_to do |format|
if #invoice.update(invoice_params)
format.html { redirect_to #invoice, notice: 'Invoice was successfully updated.' }
format.json { render :show, status: :ok, location: #invoice }
else
format.html { render :edit }
format.json { render json: #invoice.errors, status: :unprocessable_entity }
end
end
end
# DELETE /invoices/1
# DELETE /invoices/1.json
def destroy
#invoice.destroy
respond_to do |format|
format.html { redirect_to invoices_url, notice: 'Invoice was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_invoice
#invoice = Invoice.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def invoice_params
params.require(:invoice).permit(:number, :currency, :date, :duedate, :btwtotal,
:subtotal, :total, :footer, customers_attributes: [:id, :company_name, :address_line_1, :zip_code, :_destroy],
companies_attributes: [:id, :btw_number, :iban_number, :kvk_number, :company_name, :_destroy],
products_attributes: [:id, :quantity, :description, :unitprice, :btw, :total])
end
end
Any idea what's going on? Help would be much appreciated!
You can simply use built in methods provided by cocoon gem for link_to_add_association,
reference:
https://github.com/nathanvda/cocoon#link_to_add_association
<%= link_to_add_association 'Item toevoegen', f, :products,:"data-association-insertion-node" => "tbody#{id of tbody encapsulating your fields_for}",:"data-association-insertion-method" => "append", class: 'btn btn-primary btn-success' %>
P.S this is my first answer in stackoverflow, so I apologize in advance if I wasn't clear enough.
You can refer to Control the Insertion Behaviour section of cocoon gem for more reference to insert nested fields.
For example,
$(document).ready(function() {
$("#owner a.add_fields").
data("association-insertion-method", 'append').
data("association-insertion-traversal", 'closest').
data("association-insertion-node", '#parent_table');
});

Simple form for submit button doesn't do anything

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 %>

ArgumentError in SongsController#create missing required :bucket option

I've been trying to get paperclip working with amazon s3 all day and I'm gettin' pretty close.
Albeit, how do I get around this error? I've included the bucket in the song model so I'm not sure what it's asking for. Once this is solved it should work.
Error:
ArgumentError in SongsController#create
missing required :bucket option
respond_to do |format|
if #song.save
format.html { redirect_to #song, notice: 'Song was successfully created.' }
format.json { render action: 'show', status: :created, location: #song }
else
song.rb
class Song < ActiveRecord::Base
acts_as_voteable
belongs_to :user
has_many :comments, :dependent => :destroy
has_many :genre_songs
has_many :genres, through: :genre_songs
has_attached_file :track,
:storage => :s3,
:path => '/:class/:attachment/:id_partition/:style/:filename',
:url => ":s3_domain_url",
:bucket => ENV['bucketname']
validates_attachment :track, :presence => true
validates_presence_of :url
validates :title, length: { minimum: 10 }
validates :url, length: { maximum: 300 }
def self.tagged_with(name)
Genre.find_by_name!(name).songs
end
def tag_list
genres.map(&:name).join(", ")
end
def tag_list=(names)
self.genres = names.split(",").map do |n|
Genre.where(name: n.strip).first_or_create!
end
end
end
paperclip.rb
# config/initializers/paperclip.rb
Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename'
production.rb and development.rb
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['my bucketname'],
:access_key_id => ENV['my access key'],
:secret_access_key => ENV['my secret access key']
}
}
show.html.erb
<p id="notice"><%= notice %>
<p>
<%= #song.title %> | ( <%= #song.url %> )
<br />
<span class="subtext"><span class="votes_<%= #song.id %>"><%= pluralize(#song.votes.count, 'like') %>,</span>
posted <%= time_ago_in_words(#song.created_at) + " ago" %>
<small><span class="comments"></small> | <%= pluralize(#song.comments.size, 'comment') %></span></small><br /></span></span>
</p>
<p>
<%= audio_tag (#song.track.url), controls: "controls", alt: "Please use chrome, ie, or safari", preload: :auto %>
</p>
<p>Genres: <%= raw #song.genres.map(&:name).map { |t| link_to t, genre_path(t) }.join(', ') %></p>
<%#= link_to 'Show', song, class: "button small secondary" %>
<%= link_to('Edit', edit_song_path(#song), class: "button small secondary") if can? :update, #song %>
<%#= link_to 'Back', songs_path, class: "button small secondary" %>
<br /><br />
<%= render :partial => 'comments/form' %>
<div class="replies">
<% unless #song.comments.empty? %>
<h5><%= pluralize(#song.comments.size, 'comment') %></h5>
<br />
<% end %>
<% if #song.comments.empty? %>
<p>There are no comments...</p>
<% else %>
<div id="comments">
<% for comment in #song.comments %>
<div class="comment">
<strong><%= link_to_unless comment.site_url.blank?, h(comment.author_name), h(comment.site_url) %></strong>
<em>on <%= comment.created_at.strftime('%b %d, %Y at %H:%M') %></em>
<%=simple_format comment.content %><hr>
<p>
<%= link_to("Edit", edit_comment_path(comment)) if can? :update, #comment %>
<% end %>
<%= link_to("Destroy", comment, :method => :delete, :confirm => "Are you sure?") if can? :destroy, #comment %>
</p>
</div></div>
<% end %>
</div></div>
song_controller.rb
class SongsController < ApplicationController
before_filter :authenticate_user!, only: [:create ,:edit, :update, :destroy, :vote_for_song]
before_action :set_song, only: [:show, :edit, :update, :destroy, :vote_for_song]
def vote_for
#song = Song.find(params[:id])
current_user.vote_for(#song)
#song.plusminus = #song.votes_for
#song.save
respond_to do |format|
format.js { render 'update_votes' }
end
end
def vote_against
#song = Song.find(params[:id])
current_user.vote_against(#song)
respond_to do |format|
format.js { render 'update_votes' }
end
end
def new_songs
#songs = Song.order "id DESC"
end
# GET /Songs
# GET /Songs.json
def index
if params[:genre]
#songs = Song.tagged_with(params[:genre]).paginate(:page => params[:page], :per_page => 15)
else
#songs = Song.order('plusminus').paginate(:page => params[:page], :per_page => 15)
end
end
# GET /Songs/1
# GET /Songs/1.json
def show
#comment = Comment.new(song: #song)
end
# GET /Songs/new
def new
#song = Song.new
end
# GET /Songs/1/edit
def edit
end
# POST /Songs
# POST /Songs.json
def create
#song = Song.new(song_params)
respond_to do |format|
if #song.save
format.html { redirect_to #song, notice: 'Song was successfully created.' }
format.json { render action: 'show', status: :created, location: #song }
else
format.html { render action: 'new' }
format.json { render json: #song.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /Songs/1
# PATCH/PUT /Songs/1.json
def update
respond_to do |format|
if #song.update(song_params)
format.html { redirect_to #song, notice: 'Song was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #song.errors, status: :unprocessable_entity }
end
end
end
# Song /Songs/1
# Song /Songs/1.json
def destroy
#song.destroy
respond_to do |format|
format.html { redirect_to songs_url }
format.json { head :no_content }
end
end
private
def set_song
#song = Song.find(params[:id])
end
def song_params
params.require(:song).permit(:title, :artist, :url, :track, :user_id, :tag_list)
end
end
In dev and prod env you call:
ENV['my bucketname']
In model:
ENV['bucketname']
Also a good name for env variable would be:
ENV['MY_BUCKETNAME']
In your case:
ENV['AWS_BUCKET']
config.paperclip_defaults = {
:storage => :s3,
:bucket => ENV['BUCKETNAME'],
:s3_credentials => { :access_key_id => ENV['my access key'], :secret_access_key => ENV['my secret access key'] } }

getting the selected value from the drop down in rails

enter code here
<h1>Add New Investment Opportunity</h1>
<%= form_for Investopp.new do |f| %>
<div class="field">
<%= f.label :state_id %><br/>
<%= f.collection_select :state_id, Investopp.year_lookup(#state_ids), :label, :value, include_blank: true %>
</div>
<div class="field">
<%= f.label :city_id, "city" %><br />
<%= f.grouped_collection_select :city_id, Investopp.year_lookup(#state_ids), :cities, :value, :id,:name, include_blank: true %>
</div>
<% end %>
<%= link_to 'Back', investopps_path %>
<%= link_to 'Search', investopps_browsedisplay_path %>
class Investopp < ActiveRecord::Base
attr_accessible :Address, :Buildingname, :Desiredinvrole, :Details, :Prefferednoofinvestors, :Salesprice, :Weblisting, :photo, :user_id, :state_id, :city_id, :state, :city
has_attached_file :photo, :styles => { :small => "200x200>" }
belongs_to :user
validates :Buildingname, presence: true
validates :Address, presence: true
validates :Desiredinvrole, presence: true
validates :Weblisting, presence: true
validates :Details, presence: true
has_many :states
has_many :cities
def find_state(id)
if !id || id==0
id=1
end
#states= State.find(id)
#states.name
end
def find_city(id)
if !id || id==0
id=1
end
#cities= City.find(id)
#cities.name
end
def self.year_lookup(state_ids)
#create an emptycollection to hold the LabelValue Objects
years = []
state_ids.each do |yr| y = LabelValue.new()
y.label = yr
y.value = State.find_by_id(yr).name
years.push(y)
end
years
end
def self.state_lookup(state_ids)
years = []
state_ids.each do |yr| y = State.new()
y= State.find_by_id(yr)
years.push(y)
end
years
end
end
class LabelValue
# name the accessors. Label and Value
attr_accessor :label, :value
def cities
cityids=[]
state_cities=[]
investopps=Investopp.find(:all)
investopps.each do |i|
puts i.city_id
cityids <<i.city_id
end
cityids.uniq!
states=State.find_by_id(label)
cityids.each do |c|
if states.cities.find_by_id(c)
state_cities<< states.cities.find_by_id(c)
end
end
state_cities
end
end
class InvestoppsController < ApplicationController
# GET /investopps
# GET /investopps.json
def index
#investopps = Investopp.where(:user_id => current_user.id)
respond_to do |format|
format.html # index.html.erb
format.json { render json: #investopps }
end
end
# GET /investopps/1
# GET /investopps/1.json
def show
#investopp = current_user.investopps.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #investopp }
end
end
# GET /investopps/new
# GET /investopps/new.json
def new
#investopp = Investopp.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #investopp }
end
end
# GET /investopps/1/edit
def edit
#investopp = Investopp.find(params[:id])
end
# POST /investopps
# POST /investopps.json
def create
#params[:investopp][:state_id]= "gopi"
#params[:investopp][:city_id]= "33"
#investopp = current_user.investopps.build(params[:investopp])
respond_to do |format|
if #investopp.save
format.html { redirect_to #investopp, notice: 'Investopp was successfully created.' }
format.json { render json: #investopp, status: :created, location: #investopp }
else
format.html { render action: "new" }
format.json { render json: #investopp.errors, status: :unprocessable_entity }
end
end
end
# PUT /investopps/1
# PUT /investopps/1.json
def update
#investopp = Investopp.find(params[:id])
respond_to do |format|
if #investopp.update_attributes(params[:investopp])
format.html { redirect_to #investopp, notice: 'Investopp was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #investopp.errors, status: :unprocessable_entity }
end
end
end
# DELETE /investopps/1
# DELETE /investopps/1.json
def destroy
#investopp = Investopp.find(params[:id])
#investopp.destroy
respond_to do |format|
format.html { redirect_to investopps_url }
format.json { head :no_content }
end
end
def lis
#state_names=[]
#state_ids=[]
#city_ids= []
#city_names=[]
#investopp = Investopp.find(:all)
#investopp.each do |item|
#state_names<< State.find_by_id(item.state_id).name
#state_ids<< item.state_id
#city_names<< City.find_by_id(item.city_id).name
#city_ids << item.city_id
end
puts #state_ids.uniq!{|i| i}
puts #city_ids.uniq!{|i| i}
puts "gopi"
respond_to do |format|
format.html { render "investopps/lis", :locals => { :state_ids => #state_ids, :city_ids => #city_ids, :investopps => #investopp } }
format.json { render json: #investopp }
end
end
end
Instead of using <%= link_to 'Search', investopps_browsedisplay_path %> you should use <%= f.submit %> and specify the action correctly. So your form view will look like this:
<h1>Add New Investment Opportunity</h1>
<%= form_for Investopp.new, :action => investopps_browsedisplay_path do |f| %>
<div class="field">
<%= f.label :state_id %><br/>
<%= f.collection_select :state_id, Investopp.year_lookup(#state_ids), :label, :value, include_blank: true %>
</div>
<div class="field">
<%= f.label :city_id, "city" %><br />
<%= f.grouped_collection_select :city_id, Investopp.year_lookup(#state_ids), :cities, :value, :id,:name, include_blank: true %>
</div>
<%= link_to 'Back', investopps_path %>
<%= f.submit 'Search' %>
<% end %>
Then you'll also need a controller method handling things as the investopps_browsedisplay_path route, which I don't see in your code anywhere. This, of course, is not a RESTful way to handle this, and there's a needed caveat that your architecture will probably confuse the problem, but so far as sending the form data, the correct way to do it is with a form submit, not a link_to, which solves the basic problem at hand.

Resources