Rails 4 - NoMethodError undefined method - ruby-on-rails-4

I got a NoMethodError when i called <%= #post.admin_user.name %>, don't know how to fix it.
Extracted source (around line #4):
<h1><%= #post.title %></h1>
<p><%= #post.body %></p>
<small>Post created at <%= #post.created_at.strftime('%b %d. %Y') %></small><br/><br/>
<%= #post.admin_user.name %>
<p>Category: <%= link_to #post.category.name, category_path(#post.category.id) %></p>
<%= link_to 'Edit Post', edit_post_path %> | <%= link_to 'Go Back', posts_path %> | <%= link_to 'Delete Post', #post, :confirm => "Don't do it man!", :method => :delete %>
</div>
Showing c:/Sites/blog/app/views/posts/show.html.erb where line #5 raised:
undefined method `name' for nil:NilClass
This is my posts_controller.rb
class PostsController < ApplicationController
def index
#post = Post.all
end
def new
#post = Post.new
#category = Category.all
end
def create
#post = Post.new(post_params)
if #post.save
redirect_to posts_path, :notice => 'Your post has been posted!'
else
render 'new'
end
end
def post_params
params.require(:post).permit(:title, :body, :category_id, :admin_user_id, :admin_user, :name)
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update_attributes(post_params)
redirect_to post_path, :notice => 'Your post has been updated.'
else
render 'new'
end
end
def show
#post = Post.find(params[:id])
#user = AdminUser.all
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path, :notice => 'Your post has been deleted.'
end
end
This is my post.rb
class Post < ActiveRecord::Base
belongs_to :category
belongs_to :admin_user
end
My admin_user.rd
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
end

Related

rails 4 semantic ui multi-select show user selections on edit

I am trying to implement multi-select in a form in rails 4, using Semantic UI. I want users to be able to select multiple categories for each post. So far, I am able to display the dropdown select field which pulls all the categories from the database as follows:
<%= form_for #post, :html => {:class => "ui form bk-form group"} do |f| %>
<label>Post title:</label><br />
<%= f.text_field :title, autofocus: true %>
<label>Choose a category:</label><br />
<%= f.select(:category_ids,options_for_select(Category.all.collect{|x| [x.name,x.id,class:'item']}),{prompt:'Select categories'}, multiple: true, class:'ui fluid dropdown selection multiple')%>
<% end %>
With this, I am able to create and save posts and the data is inserted in the database. However, when I try to edit an article, the pre-selected categories do not show. I have tried to set the value: #post.categories option in the select field and still cannot get the existing categories to show. Thanks in advance for your thoughts.
UPDATED
Models are as follows:
class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories
end
class Category < ActiveRecord::Base
has_many :post_categories
has_many :posts, through: :post_categories
end
class PostCategory < ActiveRecord::Base
belongs_to :post
belongs_to :category, :counter_cache => :posts_count
end
Then my posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:edit, :update, :show]
def index
#posts = Post.all
end
def new
end
def create
#post = Post.new(post_params)
#post.user = current_user
if #post.save
flash[:notice] = "Post was successfully created"
redirect_to user_posts_path
else
flash[:alert] = "Oh Snap!! We could not save your post"
render 'new'
end
end
def edit
end
def update
if #post.update(post_params)
flash[:notice] = "Post was successfully updated"
redirect_to user_posts_path
else
flash[:alert] = "Oh Snap!! We could not update your post"
render 'edit'
end
end
private
def post_params
params.require(:post).permit(:title, :description, :published, :tag_list, category_ids: [])
end
def set_post
#post = Post.find(params[:id])
end
end

Creating a Purchase receipt from Charges controller

I'm creating a new Purchase from the create method of the ChargesContoller.
I can successfully create the new Purchase and pass the information related to the charge.
My questions is: How can I get the order id to the Purchase?
Here' how the checkout process works:
Event > Option > Reservation > Order "has many reservations" >
in the Order show view, I have the Stripe button which creates a new charge > redirect to Purchase.
The Purchase is basically a receipt for the order. That's why I would like to show the order id and the reservations associated with the order. I know is not passing the order id because I can see it in the rails console
Should I use a different kind of association like has_many_and_belongs_to_many?
Maybe a joinTable?
I was reading at this part of the rails guides but I'm not sure if I'm looking in the right place: http://guides.rubyonrails.org/association_basics.html
or maybe is the way I'm trying to pass the order id "in the charges create" to the purchase:
purchase = Purchase.create(customer_email: params[:stripeEmail], amount: params[:amount],
customer_card: params[:stripeToken], order_id: params[:order_id], customer_id: customer.id)
Order Model:
class Order < ActiveRecord::Base
belongs_to :order_status
belongs_to :purchase
has_many :reservations
before_create :set_order_status
before_create :create_unique_identifier
before_save :total_for_no_price
before_save :update_subtotal
def to_param
uuid
end
def subtotal
reservations.collect{ |r| r.price }.sum
end
def total_for_no_price
if self.subtotal.nil?
self[:subtotal] = 0
end
end
def create_unique_identifier
self.uuid = SecureRandom.uuid
end
private
def set_order_status
self.order_status_id = 1
end
def update_subtotal
self[:subtotal] = subtotal
end
end
Purchase model:
class Purchase < ActiveRecord::Base
has_many :orders
has_many :reservations, through: :orders
end
Charges Controller:
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#order = Order.find_by_uuid(session[:order_id])
#reservations = #order.reservations
#amount = #order.subtotal.to_i * 100
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => #order.id,
:currency => 'usd'
)
purchase = Purchase.create(customer_email: params[:stripeEmail], amount: params[:amount],
customer_card: params[:stripeToken], order_id: params[:order_id], customer_id: customer.id)
if charge.save
#order_id = #order.update_attributes(order_status_id: 2)
#redirect_to #order
redirect_to purchase
reset_session
end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
Orders Controller:
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
# GET /orders
# GET /orders.json
def index
#orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
#order = Order.find_by_uuid(params[:id])
#reservations = #order.reservations
end
# GET /orders/new
def new
#order = Order.new
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
#order = Order.new(order_params)
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render :show, status: :created, location: #order }
else
format.html { render :new }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: #order }
else
format.html { render :edit }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: 'Order was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find_by_uuid(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order).permit(:subtotal, :tax, :total, :order_status_id, :uuid)
end
end
Order Show page with the charge button:
<div class="container-fluid events-container">
<div class="row">
<div class="col-sm-12">
<h4>Your Registrations:</h4>
<% #order.reservations.each do |reservation| %>
<h4><%= reservation.name %> <%= reservation.lastname %> | <%= reservation.email %> | <%= reservation.phone %></h4>
<h4><%= reservation.gender %> <%= reservation.shirt %> </h4>
<% unless reservation.team === 'N/A' %>
<h4>Team: <%= reservation.team %></h4>
<% end %>
<% unless reservation.redeemcode === 'N/A' %>
<h4>Redeem Code: <%= reservation.redeemcode %></h4>
<% end %>
<hr>
<% end %>
<h1>Order Total: <%= number_to_currency(#order.subtotal)%></h1>
<% if #order.order_status_id === 1 %>
<%= form_tag charges_path(#order) do %>
<article>
<% if flash[:error].present? %>
<div id="error_explanation">
<p><%= flash[:error] %></p>
</div>
<% end %>
</article>
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<%= Rails.configuration.stripe[:publishable_key] %>"
data-description= "Event Registration(s)"
data-amount="<%= #order.subtotal.to_i * 100%>"
data-locale="auto">
</script>
<% end %>
<% end %>
<h3>Need to Modify you order? <%= link_to 'Back to Cart', cart_path %> </h3>
</div>
</div>
</div>
I solve this by changing:
order_id: params[:order_id] to order_id: (#order.id)
in the Charges Controller
Updated Charges Controller:
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#order = Order.find_by_uuid(session[:order_id])
#reservations = #order.reservations
#amount = #order.subtotal.to_i * 100
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => #order.id,
:currency => 'usd'
)
purchase = Purchase.create(customer_email: params[:stripeEmail], amount: params[:amount],
customer_card: params[:stripeToken], order_id: (#order.id), customer_id: customer.id)
if charge.save
#order_id = #order.update_attributes(order_status_id: 2)
#redirect_to #order
redirect_to purchase
reset_session
end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end

Devise change email does not update email

I'm trying to allow users to change their email addresses which devise uses as their unique username. Even though the update gives no errors, no change is made to the email address for the user in the database.
Here are the relevant portions of code:
Form:
<%= f.fields_for :user_account, #user.user_account do |user_account| %>
<p>Edit email address for account: <%= #user.user_account.email %></p>
<div class="field">
<%= user_account.label :new_email %><br />
<%= user_account.text_field :email, autocomplete: "off", value: nil %>
</div>
<div class="field">
<%= user_account.label :password %> <i>(please confirm the password associated with this account)</i><br />
<%= user_account.password_field :current_password, autocomplete: "off" %>
</div>
<%= hidden_field_tag 'form', 'email' %>
<div class="actions">
<%= user_account.submit "Edit" %>
</div>
controller:
def update
respond_to do |format|
if params[:form] == 'email'
if #user.user_account.valid_password?(params[:user][:user_account_attributes][:current_password])
if #user.update(user_params)
format.html { redirect_to user_path(#user), :notice => 'your new email has been saved' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
else
format.html { redirect_to edit_email_path(#user), :notice => 'incorrect password (email)' }
end
else ...
the user_params method:
def user_params
params.require(:user).permit(
:first_name, :middle_initial, :last_name,
:linkedin, :website, :facebook, :video, :phone_number,
:address_1, :address_2, :city, :zip_code,
:image, :number, :years_practicing, :neighborhood, :biography, :price, :status,
user_employments_attributes: [:id, :user_id, :company, :position, :start_date, :end_date, :info, :_destroy],
user_educations_attributes: [:id, :user_id, :school, :degree_title, :start_date, :end_date, :info, :_destroy],
user_account_attributes: [:id, :user_id, :email, :password, :password_confirmation, :_destroy],
user_category_ids:[])
end
user account model:
class UserAccount < ActiveRecord::Base
# Include default devise modules. Others available are:
# , :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :user
end
Ok, so it turns out that the new email address was being saved as :unconfirmed_email, but this did not change any of the functionality of the linked account, since the account still had the old email stored as :email.
Thus I had to do
user.confirmed_at = nil
user.save(:validate => false)
in order for the user confirmation email to be resent and so that the login form would no longer accept the old password.
I am not sure, but I think, in your user model there should be
accepts_nested_attributes_for :user_account

Unable to save Join Table details to database in Rails 4

I've always had trouble with has_many :through relationships on join tables and am stuck again on where I'm going wrong. I think it might be in my controller as I'm still getting to grips with how it all works.
I have three models:
class Role < ActiveRecord::Base
has_many :assignments, inverse_of: :role
has_many :employees, :through => :assignments
accepts_nested_attributes_for :assignments
end
class Employee < ActiveRecord::Base
has_many :assignments, inverse_of: :employee
has_many :roles, :through => :assignments
accepts_nested_attributes_for :assignments
end
class Assignment < ActiveRecord::Base
belongs_to :employee, inverse_of: :assignment
belongs_to :role, inverse_of: :assignment
accepts_nested_attributes_for :employee
accepts_nested_attributes_for :role
end
I'd like to be able to set the pre-created role for an employee when creating or editing an employee. My New Employee form is as follows:
<%= semantic_form_for #employee do |f| %>
<%= render 'shared/error_messages' %>
<%= f.inputs do %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.input :password_confirmation %>
<%= semantic_fields_for :roles do |role| %>
<%= role.input :role, :as => :select, :collection => Role.all %>
<%= role.semantic_fields_for :assignments do |assignment| %>
<%= assignment.input :start_date, :as => :date_select %>
<%= assignment.input :end_date, :as => :date_select %>
<%= assignment.input :assignment_no %>
<%= assignment.input :assignment_id %>
<% end %>
<% end %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :as => :button %>
<%= f.action :cancel, :as => :link %>
<% end %>
<% end %>
and finally my Employee Controller is:
class EmployeesController < ApplicationController
before_action :set_employee, only: [:show, :edit, :update, :destroy]
def index
#employees = Employee.paginate(page: params[:page])
end
def show
end
def new
#employee = Employee.new
role = #employee.roles.build
end
def edit
#employee = Employee.find(params[:id])
end
def create
#employee = Employee.new(employee_params)
if #employee.save
#employee.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
def update
respond_to do |format|
if #employee.update(employee_params)
flash[:success] = "Profile updated"
format.html { redirect_to #employee, notice: 'Employee was successfully updated.' }
format.json { render :show, status: :ok, location: #employee }
else
format.html { render :edit }
format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
def destroy
Employee.find(params[:id]).destroy
flash[:success] = "Employee deleted"
respond_to do |format|
format.html { redirect_to employees_url, notice: 'Employee was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
#employee = Employee.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def employee_params
params.require(:employee).permit(:avatar, :email, :first_name, :last_name, :password, :assignments_attributes => [:employee_id, :role_id, :roles_attributes => [:id, :employee_id, :PID]])
end
end
I appreciate that this subject is always on Stackoverflow, but I can't seem to translate any of the problems into where I am. Any help would be greatly appreciated!
The console output is as follows:
Started POST "/employees" for 127.0.0.1 at 2015-05-16 18:05:34 +0200
source=rack-timeout id=d5933405c94d9c2e8bca3332564528ec timeout=60000ms service=25ms state=active
Processing by EmployeesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"TgHHELkt2zXUtS474WwGeHcmfKKw/broHxRdhlsF1P4JyGoa+03rchb6mfxbOSXKdrPgcJMeBCyIlCMHqPlQBA==", "employee"=>{"first_name"=>"John", "last_name"=>"Smith", "email"=>"john#smith.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "roles"=>{"role"=>"2", "assignments"=>{"start_date(1i)"=>"2012", "start_date(2i)"=>"7", "start_date(3i)"=>"5", "end_date(1i)"=>"2016", "end_date(2i)"=>"3", "end_date(3i)"=>"1", "assignment_no"=>"4", "assignment_id"=>"A3392822"}}, "button"=>""}
Unpermitted parameter: password_confirmation
(0.2ms) BEGIN
source=rack-timeout id=d5933405c94d9c2e8bca3332564528ec timeout=60000ms service=1113ms state=active
SQL (70.3ms) INSERT INTO "employees" ("email", "first_name", "last_name", "password_digest", "created_at", "updated_at", "activation_digest") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id" [["email", "john#smith.com"], ["first_name", "John"], ["last_name", "Smith"], ["password_digest", "$2a$10$g3PNppheVZ8AFnnKuWg6secBdGev0NlCXjUx.RXsky03Xl9L3CubO"], ["created_at", "2015-05-16 16:05:35.422312"], ["updated_at", "2015-05-16 16:05:35.422312"], ["activation_digest", "$2a$10$L0yFuvmlJon7fWod6lHj..O7yDRaqwqTlTkJgD7Evqx.dA4pDTlBC"]]
(133.0ms) COMMIT
(I'm working on a very slow computer!)

paperclip error while displaying images

i get an error
undefined method `photo' for #<Post::ActiveRecord_Relation:0x00000004ad42e8>
my posts.index.html.erb
<%= image_tag #post.photo.url(:small) %>
gives me the above error and if i iterate
<% #post.each do |image| %>
<%= image_tag image.photo.url %>
<% end %>
i get this new error
SQLite3::SQLException: no such column: position: SELECT "posts".* FROM "posts" ORDER BY position ASC
here is my model, post.rb
Class Post < ActiveRecord::Base
require 'digest/md5'
has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png",
:path => ":rails_root/public/assets/images/:id/:style/:basename.:extension"
validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
validates_attachment_size :photo, :less_than => 5.megabytes
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']
include PublicActivity::Model
tracked
end
and my posts_controller.rb
class PostsController < ApplicationController
before_action :authenticate_user!
def index
##hotels = hotels.new()
#activities = PublicActivity::Activity.order("created_at desc")
#post = Post.order('position ASC')
respond_to do |format|
format.html # show.html.erb
format.json { render json: #picture }
end
end
def show
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #picture }
end
end
def new
#post = Post.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: #picture }
end
end
def create
##post = Post.create( user_params )
#post = Post.new(params[:posts].permit(:hotels, :photo, :number, :price, :guest_house, :restaurant,:lodges, :description, :region))
if #post.save
redirect_to(:controller => 'homes',:action=> 'index')
else
render('new')
end
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
#post = Post.update_attributes()
end
def delete
#post = Post.find(params[:id])
end
#def user_params
#params.require(:post).permit(:photo)
#end
end
i also have the public activity gem installed on my app and when i try to display the photos using
<%= link_to activity.trackable.photo %>
i get a link to where the photo was saved but not the actual image as shown below. help me out
Ah I finally realized my mistake. i used the link_to tag instead of the image_tag