Form data is not stored in DB - ruby

My models:
class LineItem < ActiveRecord::Base
attr_accessible :itemable, :adults, :children
belongs_to :itemable, polymorphic: true
belongs_to :lead
belongs_to :cart
end
class Lead < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def add_line_items_from_cart(cart)
cart.line_items.each do |item|
item.cart_id = nil
line_items << item
end
end
end
class House < ActiveRecord::Base
has_many :line_items, :as => :itemable
end
class Appartment < ActiveRecord::Base
has_many :line_items, :as => :itemable
end
item_controller
def create
#line_item = #cart.line_items.build itemable: #object
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item.cart,
notice: 'Vakantiehuis toegevoegd in lijst.' }
format.json { render action: 'show',
status: :created, location: #line_item }
else
format.html { render action: 'new' }
format.json { render json: #line_item.errors,
status: :unprocessable_entity }
end
end
end
private
def create_object
id = params[:house_id] || params[:appartment_id]
model = "House" if params[:house_id]
model = "Apartment" if params[:appartment_id]
model = model.constantize
#object = model.find(id)
end
lead_controller
def create
#lead = Lead.new(lead_params)
#lead.add_line_items_from_cart(#cart)
#lead.save
end
cart_controller
def create
#cart = Cart.new(cart_params)
end
private
def cart_params
params[:cart]
end
When the items are added from the house and aparment page..the visitor goes to the cart show template. The visitor can fill in number of adutls and children by a form (select).
- #cart.line_items.each do |item|
%tr.CartProduct
%td
.CartDescription
%p
= link_to item.itemable.name, polymorphic_url([item.itemable.country, item.itemable.region, item.itemable])
%td.CartProductThumb
%div
- item.itemable.attachments.take(1).each do |a|
= link_to(image_tag(a.file.url(:thumb)))
%td
.col-md-10
= form_for(item) do |f|
= f.select :adults, ['1', '2', '3', '4', '5'], :class => 'form-control'
%td
.col-md-10
= form_for(item) do |f|
= f.select :children, ['1', '2', '3', '4', '5'], :class => 'form-control'
= button_to "Checkout", new_lead_path, method: :get
The [cart_id] and the polymorphic [itemable_type][itemable_id]values are correctly stored in the line_items table, but not the form data :adults and children. What am i doing wrong ? Thanks remco
logfile:
Started POST "/nl/leads" for 127.0.0.1 at 2014-09-04 11:55:25 +0200
Processing by LeadsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jmWa/Q/+SGsS+ed7zEB5+w5tiY2ywkEx3dQeVt9roKs=", "lead"=>{"firstname"=>"test ", "lastname"=>"", "email"=>"", "extra"=>"", "telephone"=>""}, "commit"=>"submit", "nl"=>"nl"}
Cart Load (0.2ms) SELECT `carts`.* FROM `carts` WHERE `carts`.`id` = 25 LIMIT 1
LineItem Load (0.2ms) SELECT `line_items`.* FROM `line_items` WHERE `line_items`.`cart_id` = 25
(0.1ms) BEGIN
SQL (0.3ms) INSERT INTO `leads` (`created_at`, `email`, `extra`, `firstname`, `lastname`, `telephone`, `updated_at`) VALUES ('2014-09-04 09:55:25', '', '', 'test ', '', '', '2014-09-04 09:55:25')
SQL (0.2ms) UPDATE `line_items` SET `lead_id` = 8, `updated_at` = '2014-09-04 09:55:25' WHERE `line_items`.`id` = 191
(8.8ms) COMMIT
Redirected to http://0.0.0.0:3000/nl/leads/8
Completed 302 Found in 40ms (ActiveRecord: 9.7ms)

Related

Rails - Unknown Attribute - Unable to add a new field to a form on create/update

Hello I am new to Rails.
Here is my controller/projects_controller.rb code
def create
#project = current_user.projects.new(project_params)
##project.website = params[:website]
respond_to do |format|
if #project.save
Member.create!(
user_id: current_user.id,
project_id: #project.id,
project_manager: true,
status: "ready")
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render :show, status: :created, location: #project }
else
format.html { render :new }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def update
##project.website = params[:website]
respond_to do |format|
# if (#project.active_was == true) &&
# disabled = true
# end
if #project.update(project_params)
# if disabled && (#project.active == false)
# flash[:modal] = true
# end
#project.website = params[:website]
format.html { redirect_to #project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: #project }
else
format.html { render :edit }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def project_params
params.require(:project).permit(
:university_id,
:project_name,
:location,
:tagline,
:photos,
:industry,
:category,
:description,
:category_id,
:expertise_string,
:website,
:active,
:slug,
:project_groups_attributes => [:id, :active, :university_id, :user_group_id]
)
end
Here is the code for my model/project.rb
class Project < ActiveRecord::Base
# has_and_belongs_to_many :users
has_many :members, :dependent => :destroy
has_many :users, :through => :members
has_one :survey
has_many :project_groups, foreign_key: "project_id", dependent: :destroy
has_many :groups, :through => :project_groups, :source => :university
accepts_nested_attributes_for :project_groups, :allow_destroy => true
has_many :project_expertises, foreign_key: "project_id",
dependent: :destroy
has_many :expertises, :through => :project_expertises, :source => :expertise
belongs_to :category
belongs_to :website
Here is my db/migrate/[timestamp]_create_projects.rb code
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.integer :university_id
t.string :project_name
t.string :tagline
t.string :photos
t.string :industry
t.integer :category
t.text :description
t.text :website
t.timestamps
end
end
end
Why can I not add the 'website' field to this? Is there something more that I have to do?
As per your comment there is not any Website model available so there is not any meaning of putting association:
Simply remove this line from your project model
belongs_to :website
In Project model you've specified relation belongs_to :website. In migration schema instead of:
t.text :website
must be something like that:
t.references :website, index: true, foreign_key: true
When you generate model instead of
rails g ... website:text use rails g ... website:references.
ActiveRecord can't find foreign key to associate Project with Website.

Include ajax comments in index in rails 4

I have ajax comments in my rails app and it all works in the posts show but I'd like to add the form to render the comments in the index page.
I'm using sorl when rendering the index page and I tried to include comments in the post model like this:
searchable(:include => :comments) do
code....
end
but that doesn't render the comments below the posts in the index page, even though I have this in the view
<%= render :partial => 'comments/comment',:collection => #comments, :as => :comment %>
So to help you understand, here is all the code:
_post.html.erb:
<%= simple_form_for [post, Comment.new], :url => comments_path, :remote => true do |f| %>
<%= image_tag current_user.avatar.url(:small) %>
<%= f.input :body, placeholder: 'write a comment...', :input_html => { :rows => "1"}, :label => false %>
//the below two lines do not work, the commentable_id is 0 and commentable_type is blank
//post.comments.commentable_id doesn't work either
<%= f.input :commentable_id, :as => :hidden, :value => Comment.new.commentable_id %>
<%= f.input :commentable_type, :as => :hidden, :value => Comment.new.commentable_type %>
<%= button_tag(type: 'submit', :id => 'commentsend') do %>
<i class="fa fa-check"></i>
<% end %>
<% end %>
<%= render :partial => 'comments/comment',:collection => #comments, :as => :comment %>
Posts_controller:
def index
#user_count = User.where(:school => current_user.school).count
#blub_count = Post.where(:category => "status").where(:school => current_user.school).count
#items_count = Post.where(:school => current_user.school).where.not( :category => "status").count
#search = Post.search(:include => :comments) do #Post.search do
fulltext params[:search]
with(:school, current_user.school)
paginate :page => params[:page], :per_page => 20
order_by(:updated_at, :desc)
end
#posts = #search.results
respond_to do |format|
format.js
format.html
end
end
def show
#post = Post.find(params[:id])
#comments = #post.comment_threads.order('created_at desc')
#new_comment = Comment.build_from(#post, current_user, "")
end
comments_controller:
def create
#comment_hash = params[:comment]
#obj = #comment_hash[:commentable_type].constantize.find(#comment_hash[:commentable_id])
# Not implemented: check to see whether the user has permission to create a comment on this object
#comment = Comment.build_from(#obj, current_user.id, #comment_hash[:body])
if #comment.save
render :partial => "comments/comment", :locals => { :comment => #comment }, :layout => false, :status => :created
else
render :js => "alert('error saving comment');"
end
end
comments model:
acts_as_nested_set :scope => [:commentable_id, :commentable_type]
validates :body, :presence => true
#validates :user, :presence => true
# NOTE: install the acts_as_votable plugin if you
# want user to vote on the quality of comments.
#acts_as_votable
belongs_to :commentable, :polymorphic => true
# NOTE: Comments belong to a user
belongs_to :user
belongs_to :post
# Helper class method that allows you to build a comment
# by passing a commentable object, a user_id, and comment text
# example in readme
def self.build_from(obj, user_id, comment)
new \
:commentable => obj,
:body => comment,
:user_id => user_id
end
#helper method to check if a comment has children
def has_children?
self.children.any?
end
# Helper class method to lookup all comments assigned
# to all commentable types for a given user.
scope :find_comments_by_user, lambda { |user|
where(:user_id => user.id).order('created_at DESC')
}
# Helper class method to look up all comments for
# commentable class name and commentable id.
scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id|
where(:commentable_type => commentable_str.to_s, :commentable_id => commentable_id).order('created_at DESC')
}
# Helper class method to look up a commentable object
# given the commentable class name and id
def self.find_commentable(commentable_str, commentable_id)
commentable_str.constantize.find(commentable_id)
end
The comments form shoudl be like this:
<%= simple_form_for Comment.build_from(post, current_user, ""), :url => comments_path, :remote => true do |f| %>
I have to assign the comment the current post ID(commentable_id) and current user id for commentable_type to build the comment
in the view, to render the comments I used
<%= render post.comment_threads.order('created_at desc') %>
the only issue is the the render is ignoring the div

Unpermitted parameters - Rails 4.1.1, Ruby 2.1.2

I cannot seem to get to the bottom of where I am going wrong. My "order.rb" fields populate ok, but I can't get the "order_row" table values to populate. I just keep getting the following error in terminal(not worried about date for now, should be ok with that)...
Unpermitted parameters: date(i), order_row
Customer model(customer.rb)...
class Customer < ActiveRecord::Base
has_many :orders, dependent: :destroy
end
Order model(order.rb)...
class Order < ActiveRecord::Base
belongs_to :customer
has_many :order_rows, dependent: :destroy
accepts_nested_attributes_for :order_rows
end
Order_Row model(order_row.rb)
class OrderRow < ActiveRecord::Base
belongs_to :order
end
(orders_controller.rb)....
def new
#order = Order.new
end
def create
#order = Order.new(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to(#order, :notice => 'Order was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
private
def order_params
params.require(:order).permit(:customer_id, :date, :total,
:order_row_attributes => [:description, :quantity, :price, :order_id])
end
Form code on new.html.haml
= semantic_form_for #order do |f|
= f.input :customer_id, :as => :select, :collection => Hash[Customer.all.map{|c| [c.company,c.id]}]
= f.input :date
= f.fields_for :order_row do |ff|
= ff.input :description
= ff.input :quantity
= ff.input :price
= ff.hidden_field :order_id
= f.input :total
= f.action :submit, :as => :button
The problem is this line order_row_attributes.It should be order_rows_attributes. And with the date not being permitted,try changing the date attribute to some name like order_date.
This should work
private
def order_params
params.require(:order).permit(:customer_id, :order_date, :total,
:order_rows_attributes => [:description, :quantity, :price, :order_id])
end
I got it working by changing the new method to....
def new
#order = Order.new
#order.order_rows.build
end
So combination of this and Pavans answer did the trick.

ActiveAdmin calculations

I want to implement some calculation to my admin interface, so i have a product resource, at this resource you see a list of services that I do, such as airbrushing, price on application considered as, for example (1 $ per 1 square cm).
How i can better realize this idea?
I would like to see when a user pushing a button "New Product" it was a field where he writes the number of square centimeters and on the basis of these dimensions, it automatically render the required amount in the currency.
Rails 4.1.0
ActiveAdmin 1.0.0
ruby 2.1
Just now you can only type a fixed price, like fixed price for 1 product/service.
app/admin/product.rb
ActiveAdmin.register Product, { :sort_order => :name_asc } do
# Scopes
scope :all, :default => true
scope :available do |products|
products.where("available < ?", Date.today)
end
scope :drafts do |products|
products.where("available > ?", Date.today)
end
scope :featured_products do |products|
products.where(:featured => true)
end
# Permitted parameters
permit_params :article_id, :title, :description, :price, :featured, :available, :image_file_name
# Displayed columns
index do
selectable_column
column :article, :sortable => :article
column :title, :sortable => :title
column :description
# Currency helper
column :price, :sortable => :price do |cur|
number_to_currency cur.price, locale: :ru
end
column :featured
column :available
# column :image_file_name
actions
end
# Product details
show do
panel "Product Details" do
attributes_table_for product do
row("Article") { link_to product.article }
row("Title") { product.title }
row("Description") { product.description }
row("Price") { product.price }
row("Featured") { product.featured }
row("Available on") { product.available }
row("Image") { image_tag("products/" + product.image_file_name) }
end
end
end
# Filters
filter :article, :as => :select
filter :title, :as => :select # :check_boxes (for checkboxes)
filter :price, :as => :select
filter :available, :as => :select
filter :featured, :as => :check_boxes
end
app/models/product.rb
class Product < ActiveRecord::Base
# Relationship
belongs_to :article
# Named Scopes
scope :available, lambda{ where("available < ?", Date.today) }
scope :drafts, lambda{ where("available > ?", Date.today) }
# Validations
validates :article, :title, :description, :price, :available, :presence => true
validates :featured, :inclusion => { :in => [true, false] }
end
app/models/article.rb
class Article < ActiveRecord::Base
# Relationship
has_many :products, :dependent => :delete_all
# Validations
validates :title, :description, :presence => true
# Define for display a article for products as article code
def to_s
"#{title}"
end
end

How to access param values in controller in ruby on rails?

I got a task to access param values for creating new user.My controller code for create is
def newstudent
#student = Student.new(params)
puts "+++++++++++"
puts params.inspect
if #student.save
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #jtable }
end
end
end
But by doing this i had got some error in terminal.It shows like this
ActiveModel::MassAssignmentSecurity::Error (Can't mass-assign protected attributes: action, controller):
app/controllers/students_controller.rb:42:in `new'
app/controllers/students_controller.rb:42:in `newstudent'
Please help me to solve the problem?
This is my controller for add new student. By getting that error message you must reject controller and action using #student = Student.new(params.reject {|key,value| key =="controller" || key =="action"}) code.
def newstudent
#student = Student.new(params.reject {|key,value| key =="controller" || key =="action"})
if #student.save
#jtable = {'Result' => 'OK','Record' => #student.attributes}
else
#jtable = {'Result' => 'ERROR','Message'=>'Empty'}
end
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #jtable }
end
end
In rails 3.2.3 there is no mass assignment by default. You have to go your model and add attr_accessible :name, :position, :visible. Basically you have to add every attribute you want to mass assign.
class Student < ActiveRecord::Base
attr_accessible :name, :position, :visible
end
Your Student model should whitelist the attributes that can be mass-assigned using attr_accessible as in:
class Student < ActiveRecord::Base
attr_accessible :name
end

Resources