I am trying to create categories for my posts. To do so, I generated a new category model. Although I have associated the two models, I am still receiving this error:
ActiveRecord::UnknownAttributeError: unknown attribute 'category_id' for Post.
I have doublechecked the schema which does include category_id for the post table:
add_index "comments", ["post_id"], name: "index_comments_on_post_id"
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "cost"
t.integer "openspots"
t.boolean "approval"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "category_id"
end
add_index "posts", ["user_id"], name: "index_posts_on_user_id"
Here are my associations as well:
class Category < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :comments
default_scope { order('created_at DESC') }
end
Finally I wanted to include my posts controller:
class PostsController < ApplicationController
def new
# #post = Post.new
#post = Post.new
#categories = Category.all.map{|c| [ c.name, c.id ] }
end
def create
#post = Post.new(params.require(:post).permit(:title, :description, :cost, :openspots, :approval, :category_id))
#post.category_id = params[:category_id]
#post.user = current_user
if #post.save
flash[:notice] = "Post was saved."
redirect_to #post
else
flash[:error] = "There was an error saving the post. Please try again."
render :new
end
end
def update
#post = Post.find(params[:id])
#post.category_id = params[:category_id]
if #post.update_attributes(params.require(:post).permit(:title, :description))
flash[:notice] = "Post was updated."
redirect_to #post
else
flash[:error] = "There was an error saving the post. Please try again."
render :edit
end
end
def edit
#post = Post.find(params[:id])
#post.category_id = params[:category_id]
end
def destroy
end
def index
#posts = Post.all
end
def show
#post = Post.find(params[:id])
end
end
Whenever I create a new post, the post is created successfully;however, the category id is never saved.
Here is my view as well:
<h1>New Post</h1>
<div class="row">
<div class="col-md-4">
<p>Guidelines for posts</p>
<ul>
<li>Make sure it rhymes.</li>
<li>Don't use the letter "A".</li>
<li>The incessant use of hashtags will get you banned.</li>
</ul>
</div>
<div class="col-md-8">
<%= form_for #post do |f| %>
<div class="form-group">
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter post description" %>
</div>
<div class="form-group">
<%= f.label :cost %>
<%= f.number_field :cost, rows: 8, class: 'form-control', placeholder: "Enter cost" %>
</div>
<div class="form-group">
<%= f.label :openspots %>
<%= f.number_field :openspots, rows: 8, class: 'form-control', placeholder: "Enter Number of Open Spots" %>
</div>
<div class="form-group">
<%= f.label :approval %>
<%= f.check_box :approval, rows: 8, class: 'form-control', placeholder: "Check if Approval Necessary" %>
</div>
<div class="form-group">
<%= f.label :category %>
<%= f.collection_select :category_id, Category.order(:name),:id,:name, include_blank: true %>
</div>
<div class="form-group">
<%= f.submit "Save", class: 'btn btn-success' %>
</div>
<% end %>
</div>
</div>
Related
now I'm trying store data (supplier_id and outlet_id) to outlet_suppliers from create supplier form, but it shown some error which is undefined method `outlet_suppliers'. Below is my code:
suppliers controller
def new
#supplier = Supplier.new
#outlet = Outlet.all
#supplier.company_id = params[:company_id]
end
def create
#supplier = Supplier.new(supplier_params)
#company_id = Company.find(params[:supplier][:company_id])
#outlet_id = Outlet.all
if #supplier.save
#outlet_supplier = Outlet.find(params[:supplier][:outlet_id]).outlet_suppliers.create(supplier: #supplier)
redirect_to #supplier
else
render 'new'
end
end
new.html.erb
<% provide(:title, "Create Suppliers") %>
<h1>Create Supplier</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #supplier, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :address %>
<%= f.text_field :address, class: 'form-control' %>
<%= f.label :phone_number %>
<%= f.number_field :phone_number, class: 'form-control' %>
<%= f.label :outlet_id %>
<%= f.select(:outlet_id, Outlet.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.hidden_field :company_id , value: 2%>
<%= f.submit "Create Supplier", class: "btn btn-primary" %>
<% end %>
</div>
</div>
outlet_suppliers migration
create_table "outlet_suppliers", force: :cascade do |t|
t.integer "outlet_id"
t.integer "supplier_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Error show in website
issue is with your model file as pointed out by #Sergio in a comment.
#app/models/outlet_supplier.rb
class OutletSupplier < ApplicationRecord
belongs_to :outlet
belongs_to :supplier
#...
end
#app/models/outlet.rb
class Outlet < ApplicationRecord
has_many :outlet_suppliers
#...
end
I hope this will help you.
now i'm doing a grocery website. I trying to build an order form that can choose select supplier and outlet,so admin can create order by choosing which supplier and outlet, but now it come out error say unpermitted parameters.
Orders Controller
class OrdersController < ApplicationController
def supplier
#supplier = Supplier.find(params[:id])
end
def outlet
#outlet = Outlet.find(params[:id])
end
def index
#orders = Order.all
end
def show
#order = Order.find(params[:id])
end
def new
#order = Order.new
#supplier = Supplier.all
#outlet = Outlet.all
end
def create
#order = Order.new(order_params)
#supplier_id = Supplier.all
#outlet_id = Outlet.all
if #order.save
flash[:success] = "Succesful create!"
redirect_to #order
else
render 'new'
end
end
private
def order_params
params.require(:order).permit(:supplier_id,:grand_total, :order_date,
:delivery_date, :delivery_address, :outlet_id)
end
end
new.html.erb
<% provide(:title, "Create Orders") %>
<h1>Create Order</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #order, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :supplier %>
<%= f.select(:supplier, Supplier.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.label :grand_total %>
<%= f.number_field :grand_total, class: 'form-control' %>
<%= f.label :order_date %>
<%= f.date_field :order_date, class: 'form-control' %>
<%= f.label :delivery_date %>
<%= f.date_field :delivery_date, class: 'form-control' %>
<%= f.label :delivery_address %>
<%= f.text_field :delivery_address, class: 'form-control' %>
<%= f.label :outlet %>
<%= f.select(:outlet, Outlet.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.submit "Create order", class: "btn btn-primary" %>
<% end %>
</div>
</div>
Order migration table in schema
create_table "orders", force: :cascade do |t|
t.integer "supplier_id"
t.integer "grand_total"
t.date "order_date"
t.date "delivery_date"
t.string "delivery_address"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "outlet_id"
end
parameter in console
error in website
The reason you're getting
Unpermitted parameters: :supplier, :outlet
is because you're not allowing :supplier and :outlet params but :supplier_id and :outlet_id in order_params
The Fix
Change this in your view new.html.erb
<%= f.label :supplier_id %>
<%= f.select(:supplier_id, Supplier.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
<%= f.label :outlet_id %>
<%= f.select(:outlet_id, Outlet.all.collect { |l| [ l.name, l.id] }, {class: "form-select"}) %>
This should fix the issue by allowing the :supplier_id and :outlet_id params and assigning the object with proper values
How can I upload multiple images using CarrierWave?
I followed "drjorgepolanco" answer from
Rails 4 multiple image or file upload using carrierwave
but I keep getting a error
undefined method `[]' for #<AssignmentpicUploader:0x007eff7831a4d8>
Extracted source (around line #25):
ActionView::Template::Error (undefined method `[]' for #<AssignmentpicUploader:0x007eff7831a4d8>):
22:
23:
24: <div id="img">
25: <%= image_tag #assignment.picture[1].url(:large) %>
26: </div>
27:
28: </br>
app/views/assignments/show.html.erb:25
assignment.rb
class Assignment < ActiveRecord::Base
validates :name, length: { minimum: 1, maximum:120 }
validates :description, length: { minimum: 1 }
mount_uploader :picture, AssignmentpicUploader
end
assignments_controller.rb
class AssignmentsController < ApplicationController
before_action :authenticate_user!
before_filter :admin_access, only: [:new, :create, :edit, :update, :destroy]
def index
#assignments = Assignment.all.order("created_at DESC")
end
def show
#assignment = Assignment.find(params[:id])
end
def new
#assignment = Assignment.new
end
def create
#assignment = current_user.assignments.build
#assignment.name = params[:assignment][:name]
#assignment.description = params[:assignment][:description]
#assignment.picture = params[:assignment][:picture]
if #assignment.save
flash[:notice] = "Assignment was saved successfully."
redirect_to #assignment
else
flash.now[:alert] = "Error creating assignment. Please make sure there is a name and description."
render :new
end
end
def edit
#assignment = Assignment.find(params[:id])
end
def update
#assignment = Assignment.find(params[:id])
#assignment.name = params[:assignment][:name]
#assignment.description = params[:assignment][:description]
#assignment.picture = params[:assignment][:picture]
if #assignment.save
flash[:notice] = "Assignment was updated successfully."
redirect_to #assignment
else
flash.now[:alert] = "Error saving assignment. Please try again."
render :edit
end
end
def destroy
#assignment = Assignment.find(params[:id])
if #assignment.destroy
flash[:notice] = "\"#{#assignment.name}\" was deleted successfully."
redirect_to action: :index
else
flash.now[:alert] = "There was an error deleting the assignment."
render :show
end
end
private
def assignment_params
params.require(:assignment).permit(:name, :description, picture: [])
end
end
assignments/new.html.erb
...
<div class="col-md-8">
<%= form_for #assignment, :html => { :multipart => true } do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter assignment name" %>
</div>
<div class="form-group">
<%= f.label :description %>
<%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter assignment description" %>
</div>
<div class="form-group">
<%= f.label :picture %>
<%= f.file_field :picture, :multiple => true %>
</div>
<br />
<%= f.submit "Save", class: 'button' %>
<% end %>
</div>
</div>
assignments/show.html.erb
<%= image_tag #assignment.picture[1].url(:large) %>
schema.rb
create_table "assignments", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.string "picture"
end
add_index "assignments", ["user_id"], name: "index_assignments_on_user_id"
Carrierwave documentation says:
Add a column which can store an array. This could be an array column or a JSON column for example. Your choice depends on what your database supports.
Your "picture" is just a string. Add serialize :picture, JSON to your model.
My app was working perfectly an hour ago, then I added two columns, :pick_up and :send to the 'orders' table, and after that I got this error
wrong number of arguments (1 for 0)
I don't see why that should be causing this error though.
Here is orders_controller.rb:
class OrdersController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:new, :create]
before_action :set_order, only: [:show, :edit, :destroy]
def index
#orders = Order.all?
end
def new
#images = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]
#random_no = rand(5)
#random_image = #images[#random_no]
if #cart.product_items.empty?
redirect_to root_url, notice: 'Your Cart is Empty'
return
end
#order = Order.new
#client_token = Braintree::ClientToken.generate
end
def create
#order = Order.new(order_params)
if #order.save
charge
if #result.success?
#order.add_product_items_from_cart(#cart)
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
OrderNotifier.received(#order).deliver
redirect_to root_url, notice: 'Thank You for Your Order'
else
flash[:error] = 'Please Check Your Cart'
redirect_to root_url, alert: #result.message
#order.destroy
end
else
#client_token = Braintree::ClientToken.generate
render :new
end
end
def show
end
def destroy
#order.destroy
redirect_to root_url, notice: 'Order deleted'
end
private
def set_order
#order = Order.find(params[:id])
end
def order_params
params.require(:order).permit(:name, :email, :address, :city, :country, :pick_up, :send)
end
def charge
#result = Braintree::Transaction.sale(
amount: #cart.total_price_usd,
payment_method_nonce: params[:payment_method_nonce] )
end
end
This is _form.html.erb for the orders:
<%= form_for #order do |f| %>
<%= render 'msg' %>
<div class="container">
<div class="col-md-10">
<h3>Please Enter Your Details</h3>
</div>
<div class="form-group">
<div class="col-md-10">
<%= f.label :name %>
<%= f.text_field :name, size: 40, class: 'form-control' %>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<%= f.label :email%>
<%= f.email_field :email, size: 40, class: 'form-control' %>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<%= f.label :address %>
<%= f.text_area :address, cols: 40, class: 'form-control' %>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<%= f.label :city %>
<%= f.text_field :city, size: 40, class: 'form-control' %>
</div>
</div>
<div class="form-group">
<div class="col-md-5">
<%= f.label :country %>
<%= f.country_select :country, { priority_countries: [ "IS", "US", "DE", "ES", "PT" ]}, { class: "form-control" }%>
</div>
</div>
<div class="form-group">
<div id="payment-form"></div>
<div class="col-md-10">
<br>
<%= f.submit 'Place Order', class: 'buttons' %>
</div>
</div>
</div>
<% end %>
Here is the order part of schema.rb:
create_table "orders", force: :cascade do |t|
t.string "name"
t.string "email"
t.text "address"
t.string "city"
t.string "country"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "shipped", default: false
t.string "pick_up"
t.string "send"
end
I fear send is not a lucky name for an identifier because the send method.
http://ruby-doc.org/core-2.3.1/Object.html#method-i-send
I'd like to check from and to times.
If from > to, I'd like display an error.
How can I edit my code?
Althogh I tried some codes with cover, include, I haven't be able to apply them to my code.
schema.rb
...
create_table "events", force: :cascade do |t|
t.time "from"
t.time "to"
...
schedules_controller.rb
...
def new
#schedule = Schedule.new
room = #schedule.rooms.build
schedule.events.build
end
def create
#schedule = current_user.schedules.build(schedule_params)
if #schedule.save
flash[:success] = "schedule created!"
redirect_to root_url
else
render 'new'
end
end
def edit
#day_max = Room.where("schedule_id = ?", #schedule.id).maximum(:day)
end
def update
#schedule.rooms.maximum(:day)
if #schedule.update(schedule_params)
flash[:success] = "schedule updated!"
redirect_to root_url
else
render 'edit'
end
end
_schedule_form.html.erb
<%= f.label :title %>
<%= f.text_field :title, class: 'form-control' %>
<br>
<%= f.label :departure_date %>
<div class="input-group date" id="datetimepicker">
<%= f.text_field :departure_date, :value => (f.object.departure_date.strftime('%b/%d/%Y') if f.object.departure_date), class: 'form-control' %>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker').datetimepicker({format:'MMM-DD-YYYY'});
});
</script>
<br>
<div id="room">
<%= f.simple_fields_for :rooms do |a| %>
<div id="room_<%= a.object.object_id %>">
<p class="day-number-element-selector"><b>Day <%= a.index.to_i + 1 %></b></p>
<%= a.simple_fields_for :events do |e| %>
<span class="form-inline">
<p>
<%= e.input :from, label: false %>
<%= e.input :to, label: false %>
</p>
</span>
<%= e.input :title, label: false %>
<% end %>
</div>
<%= a.link_to_add "Add event", :events, data: {target: "#room_#{a.object.object_id}"}, class: "btn btn-primary" %>
<%= a.input :room %>
<% end %>
</div>
It would be appreciated if you could give me how to check and display error.
You probably want to implement a validator in your event model, as explained in the documentation.
class Event < ActiveRecord::Base
validates :to, presence: true
validates :from, presence: true
validate do |e|
if e.from.present? && e.to.present? and e.from > e.to
e.errors[:base] << "To time must be after from time"
end
end
end