The views I have created previously are all working fine. I generated a model and controller for subscriptions and have the corresponding views linked to my home page. No error is thrown, but my erb code isn't being rendered to my browser. I can add html (i.e. 'hello world' wrapped in div's).
I've tried the following.
Stripped the surrounding html code and just tried rails helper methods wrapped in erb.
Deleted and re-generated both Subscription model and subscriptions controller/views
Checked my routes.rb file for subscription-related issues
Looked at both of these related questions from SO to no avail. link1
link2
Here is a look at my code and output from webrick:
webrick output
# subscriptions/index.html.erb
<% form_for(#subscription) do |f| %>
<div class="container">
<div class="row-fluid">
<div class="span12">
<div class="widget widget-table">
<div class="widget-header">
<h3>
<i class="icon-"></i> Pay with Credit Card
</h3>
</div>
<div class="widget-content">
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td>
<% if #subscription.stripe_card_token.present? %>
Credit card has been provided.
<% else %>
<div class="control-group">
<%= label_tag :card_number, "Credit Card Number" %>
<%= text_field_tag :card_number, nil, name: nil %>
</div>
</td>
</tr>
<tr>
<td>
<div class="control-group">
<%= label_tag :card_code, "Security Code on Card (CVV)" %>
<%= text_field_tag :card_code, nil, name: nil %>
</div>
</td>
</tr>
<tr>
<td>
<div class="control-group">
<%= label_tag :card_month, "Card Expiration" %>
<%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"} %>
<%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} %>
</div>
</td>
<% end %>
</tr>
<tr>
<td>
<div id="stripe_error">
<noscript><!--Error here--></noscript>
</div>
</td>
</tr>
</tbody>
</table>
</div><!-- END CLASS widget-content -->
</div><!-- END CLASS widget widget-table -->
</div><!-- END CLASS span12 -->
</div><!-- END CLASS row-fluid -->
</div><!-- END CLASS container -->
<% end %>
# routes.rb
Whizcharts::Application.routes.draw do
resources :subscriptions, only: [:new, :create, :index]
# START devise routes
devise_for :admins, controllers: { registrations: "registrations" }# , path_names: { sign_in: "login", sign_out: "logout" }
mount Deviseadmin::Engine, at: "/deviseadmin"
devise_for :users, path_names: { sign_in: "login", sign_out: "logout" }
## END devise routes
# START mailer
# match 'admins/show', to: "admins#show"
## END mailer
# START static_pages routes
root to: "static_pages#home"
match "static_pages/about", to: "static_pages#about", as: :about
match "static_pages/pricing", to: "static_pages#pricing", as: :pricing
match "static_pages/contact", to: "static_pages#contact", as: :contact
## END static_pages routes
# START deployments routes
match "deployments/deployment_print", to: "residents#deployment_print", as: :print
# subscriptions_controller.rb
# Note: Subscription.new is in the index method temporarily to demonstrate this issue
class SubscriptionsController < ApplicationController
def index
#subscription = Subscription.new
#subscriptions = Subscription.all
end
def new
#subscription = Subscription.new
end
def show
#subscription = Subscription.find(params[:id])
end
end
# subscription.rb
class Subscription < ActiveRecord::Base
belongs_to :admin, dependent: :destroy
validates_presence_of :plan_id
attr_accessor :stripe_card_token
def save_with_payment
if valid?
customer = Stripe::Customer.create(plan: plan_id, card: stripe_card_token)
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end
end
# admin.rb
# Note: Included to demonstrate the association between the Admin and Subscription models
class Admin < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :fac_name, :fac_address, :fac_city, :fac_state, :fac_zip, :lic_num, :owner_fname, :owner_lname, :fac_phone1,:fac_phone2, :fac_phone3, :fac_phone4, :fac_phone5, :fac_email1, :fac_email2, :fac_email3, :fac_email4, :fac_email5, :initials
has_many :residents
has_many :fund_record_form2s, through: :residents
has_many :deployments
has_many :subscriptions
def full_name
"#{owner_fname} #{owner_lname}"
end
end
I am running rails 3.2.14
If I forgot something, I will put it up promptly after your notification.
You are missing the equal(=) sign.
It should be <%= form_for(#subscription) do |f| %>
You are missing the equal sign before the form_for helper.
<%= form_for %>
You need the equal sign, otherwise the ERB tags are not put on the template.
Related
Hi I have a simple app with user, venue and heart models
User Model
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :masqueradable, :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable
has_many :hearts, dependent: :destroy
has_many :venues, through: :hearts
def hearts?(venue)
venue.hearts.where(user_id: id).any?
end
end
Venue Model
class Venue < ApplicationRecord
has_many :hearts, dependent: :destroy
has_many :users, through: :hearts
end
Heart Model
class Heart < ApplicationRecord
belongs_to :user
belongs_to :venue
validates :user_id, uniqueness: { scope: :venue_id }
end
The problem I have is that when I go to create a heart through the venue view I get the ActionController::RoutingError (No route matches [POST] "/venues/2/heart/2"):
app/views/venues/show.html.erb
<div class="row mb-3">
<div class="col text-center">
<h1><%= #venue.name %></h1>
</div>
</div>
<div class="row mb-3">
<div class="col text-center">
<%= render partial: 'heart', locals: {venue: #venue} %>
</div>
</div>
app/views/venues/_heart.html.erb
<% if user_signed_in? && current_user.hearts?(venue) %>
<%= link_to venue_heart_path(venue), method: :delete, remote: true do %>
<i class="fas fa-heart fa-2x" style="color: #cc0000"></i>
<% end %>
<% else %>
<%= link_to venue_heart_path(venue), method: :post, remote: true do %>
<i class="far fa-heart fa-2x" style="color: #cc0000"></i>
<% end %>
<% end %>
<p><%= venue.hearts.count %> <%= (venue.hearts.count) == 1 ? 'Heart' : 'Hearts'%></p>
<% #venue.hearts.each do |heart| %>
<%= image_tag heart.user.avatar_url, width: 20 %>
<% end %>
here is my controller for hearts and my routes|grep venue
app/controllers/venues/hearts_controller.rb
class Venues::HeartsController < ApplicationController
before_action :authenticate_user!
before_action :find_venue!
def create
#venue.hearts.where(user: current_user).first_or_create
redirect_to venue_path(#venue), :notice => 'Hearted!'
end
def destroy
#venue.hearts.where(user: current_user).destroy_all
redirect_to venue_path(#venue), :notice => 'UnHearted, you are heartless!'
end
private
def find_venue!
#venue = Venue.find(params[:venue_id])
end
end
rake routes | grep venue
warning ../package.json: No license field
venue_heart_index GET /venues/:venue_id/heart(.:format) venues/heart#index
POST /venues/:venue_id/heart(.:format) venues/heart#create
new_venue_heart GET /venues/:venue_id/heart/new(.:format) venues/heart#new
edit_venue_heart GET /venues/:venue_id/heart/:id/edit(.:format) venues/heart#edit
venue_heart GET /venues/:venue_id/heart/:id(.:format) venues/heart#show
PATCH /venues/:venue_id/heart/:id(.:format) venues/heart#update
PUT /venues/:venue_id/heart/:id(.:format) venues/heart#update
DELETE /venues/:venue_id/heart/:id(.:format) venues/heart#destroy
venues GET /venues(.:format) venues#index
POST /venues(.:format) venues#create
new_venue GET /venues/new(.:format) venues#new
edit_venue GET /venues/:id/edit(.:format) venues#edit
venue GET /venues/:id(.:format) venues#show
PATCH /venues/:id(.:format) venues#update
PUT /venues/:id(.:format) venues#update
DELETE /venues/:id(.:format) venues#destroy
config/routes.rb
require 'sidekiq/web'
Rails.application.routes.draw do
resources :venues do
resources :heart, module: :venues
end
I really appreciate your help
As the previous answer suggests, the path you're using in the link to create a new heart for a venue is not correct.
Have a look at the route for creating a heart. It seems like it has no prefix, but the same prefix as the route before (for heart#index) applies. So the link to create a new heart should have the venue_heart_index_path(venue).
I assume you didn't use resources in your routes.rb file?
ok so with the help of #arieljuod and #clara I was able to find my solution:
the problem stemmed from the follow along i was doing from here https://github.com/gorails-screencasts/gorails-24-liking-posts/blob/master/config/routes.rb
because i had resource and not resources rails asked for a singular on the create.
venue_heart_path didnt work, venue_heart_index_path threw a
ActionController::RoutingError (uninitialized constant Venues::HeartController
Did you mean? Venues::HeartsController): error
I went back to
<%= link_to venue_hearts_path(venue), method: :post, remote: true do %>
<i class="far fa-heart fa-2x" style="color: #cc0000"></i>
<% end %>
and changed the routes to
resources :venues do
resources :hearts, module: :venues
end
and the create worked... but the delete didnt. I had to change that to:
<%= link_to venue_heart_path(venue), method: :delete, remote: true do %>
<i class="fas fa-heart fa-2x" style="color: #cc0000"></i>
<% end %>
and boom it worked
You don't have a route with that format and POST method:
venue_heart GET /venues/:venue_id/heart/:id(.:format) venues/heart#show
PATCH /venues/:venue_id/heart/:id(.:format) venues/heart#update
PUT /venues/:venue_id/heart/:id(.:format) venues/heart#update
DELETE /venues/:venue_id/heart/:id(.:format)
Use PATCH por PUT methods instead to update an object.
I am working on a hotdesking app where the users would check_availability (check_availability.html.erb) of the desks based on the date range chosen and choose from a list of available desk (new.html.erb) before it gets saved in the database.
How can i use the form input in check_availability and use it under my 'new' method?
bookings_controller.rb
class BookingsController < ApplicationController
def index
end
def check_availability
end
def new
#booking = Booking.new(booking_params)
#booking.date_range(params[:book_from], params[:book_to])
end
def create
end
def show
end
private
def booking_params
params.permit(:book_from, :book_to, :wing, :section, :number, :user_id)
end
end
booking.rb
class Booking < ApplicationRecord
belongs_to :user, optional: true
belongs_to :desk, optional: true
accepts_nested_attributes_for :desk, allow_destroy: true
cattr_accessor :current_user
attr_accessor :book_from, :book_to
def check_availability
counter = 0
Booking.all.each do |b|
current_date = Date.today
booked_start_date = b.book_from
booked_end_date = b.book_to
if b.user_id == current_user.id && current_date <= booked_end_date && booked_start_date <= current_date
counter += 1
end
end
puts counter
end
def date_range(book_from, book_to)
a = []
a.push(book_from)
a.push(book_to)
puts a
end
routes.rb
Rails.application.routes.draw do
devise_scope :user do
authenticated :user do
root 'bookings#index', as: :authenticated_root
end
unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end
devise_for :users
resources :desks
post '/users/:user_id/bookings/:id', :to => 'bookings#show'
post '/users/:user_id/bookings/new', :to => 'bookings#new'
resources :users do
resources :bookings do
collection do
get :check_availability
end
end
end
end
check_availability.html.erb
<div class="container-fluid">
<div class="row">
<div class='col-sm-6 col-sm-offset-3'>
<h1>Check Availability</h1><hr />
</div>
<div class='col-sm-6 col-sm-offset-3'>
<%= form_tag new_user_booking_path, multipart: true do %>
<div class='form-group'>
<span class='not-bold'><%= label_tag :book_from, "Book From" %>: </span></br>
<span class='date-select'><%= date_select :book_from, class: 'form-control' %></span>
</div>
<div class='form-group'>
<span class='not-bold'><%= label_tag :book_to, "Book To" %>: </span><br />
<span class='date-select'><%= date_select :book_to, class: 'form-control' %></span>
</div>
<%= submit_tag "Check Availability", class: "btn" %>
<% end %>
</div>
<br />
<div class='col-sm-6 col-sm-offset-3'>
<br />
<hr />
<button type="button" class="button">
<%= link_to "My Bookings", authenticated_root_path %>
</button>
<button type="button" class="button">
<%= link_to "Book Desk", new_user_booking_path(current_user) %>
</button>
</div>
It took me lots of tries to figure this out!
I realised it was a routing issue. The form should be doing a GET instead of a PUT request.
I changed the form_tag route in my check_availability.html.erb file to <%= form_tag(new_user_booking_path, method: "get", class: "bookings") do %> and i can now access the form inputs through the controller with params.
First of all I would like to say Im very new on rails, so Im a noob.
I'm getting this error when I try to acess the "new forum page" from an app(forum monster) root/forums/new:
ActiveRecord::RecordNotFound in ForumsController#new
Couldn't find Category with id=
Here is my user model:
class User < ActiveRecord::Base
include Gravtastic
gravtastic :size => 165, :filetype => :png, :rating => 'R'
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
validates :email, :username, :presence => true, :uniqueness => true
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :username, :email, :password, :password_confirmation, :remember_me
has_many :topics, :dependent => :destroy
has_many :posts, :dependent => :destroy
def admin?
true if self.username == 'admin'
end
end
Here is my routes:
Community::Application.routes.draw do
resources :categories, :except => [:index, :show]
resources :forums, :except => :index do
resources :topics, :shallow => true, :except => :index do
resources :posts, :shallow => true, :except => [:index, :show]
end
root :to => 'categories#index', :via => :get
end
devise_for :users
root :to => 'categories#index', :via => :get
resources :users
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => "welcome#index"
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end
and here is my view file:
<div class="module">
<div class="module_header"><%= action_name.humanize %> Forum</div>
<div class="module_subheader smaller">
<em>To create a category, leave the category field unselected.</em>
</div>
<div class="module_body">
<%= form_for #forum do |f| %>
<% if #forum.errors.any? %>
<% flash.now[:error] = #forum.errors.full_messages.join(', and ') %>
<% end %>
<div class="fieldset">
<span class="label indent smaller">
<%= f.label :category_id %><br />
<small>(Required)</small>
</span>
<span class="input indent smaller">
<%= f.collection_select :category_id, Category.all, :id, :title %>
</span>
<div class="clear"></div>
</div>
<div class="fieldset">
<span class="label indent smaller">
<%= f.label :title %><br />
<small>(Required)</small>
</span>
<span class="input indent smaller"><%= f.text_field :title, :size => 75 %></span>
<div class="clear"></div>
</div>
<div class="fieldset">
<span class="label indent smaller">
<%= f.label :description %><br />
<small>(Required)</small>
</span>
<span class="input indent smaller"><%= f.text_area :description, :cols => 60, :rows => 5 %></span>
<div class="clear"></div>
</div>
<div class="fieldset">
<span class="label indent smaller">
<%= f.label :position %>
</span>
<span class="input indent smaller"><%= f.text_field :position %></span>
<div class="clear"></div>
</div>
<div class="fieldset">
<span class="label indent smaller"></span>
<span class="input indent smaller">
<%= f.check_box :state %>
<%= f.label :state %>
</span>
<div class="clear"></div>
</div>
</div>
<div class="module_footer">
<div class="fieldset">
<span class="input"><%= f.submit "submit" %> or <%= link_to "cancel", #forum.nil? ? forum_path(#forum) : forums_path %></span>
<div class="clear"></div>
</div>
</div>
<% end %>
</div>
</div>
EDIT:
Here is my Forum controller:
class ForumsController < ApplicationController
load_and_authorize_resource :category
load_and_authorize_resource :forum, :through => :category, :shallow => true
def create
if #forum.save
flash[:notice] = "Forum was successfully created."
redirect_to forums_url
else
render :action => 'new'
end
end
def update
if #forum.update_attributes(params[:forum])
flash[:notice] = "Forum was updated successfully."
redirect_to forum_url(#forum)
end
end
def destroy
if #forum.destroy
flash[:notice] = "Category was deleted."
redirect_to forums_url
end
end
end
and also here is my Categories controller:
class CategoriesController < ApplicationController
load_and_authorize_resource :category
def create
if #category.save
flash[:notice] = "Category was successfully created."
redirect_to forums_url
else
render :action => 'new'
end
end
def update
if #category.update_attributes(params[:category])
flash[:notice] = "Category was updated successfully."
redirect_to forums_url
end
end
def destroy
if #category.destroy
flash[:notice] = "Category was deleted."
redirect_to forums_url
end
end
end
EDIT2:
My gemfile:
source 'http://rubygems.org'
gem 'rails', '3.2.14'
gem 'sqlite3'
gem 'forum_monster', '~> 1.0.3'
gem 'devise'
gem 'cancan'
gem 'gravtastic', :git => 'https://github.com/chrislloyd/gravtastic.git'
gem 'bb-ruby'
group :development do
gem 'hirb'
gem 'heroku'
end
group :production do
gem 'unicorn'
end
Sorry for being noob, Im new on rails.
I don't quite have enough experience with CanCan to say this with as much confidence as I'd like to, but I think your load_and_authorize_resource is off in the ForumsController.
I think what you're doing would make sense if your resources were like this:
resources :categories do
resources :forums
...
However, without this nesting, the load_and_authorize_resource :category in the forums controller is looking to initialize #category with data that does not exist.
If my suspicions are right (and I may well be misinterpreting what's going on here), I think the fix should be easy - just reduce the load_and_authorize_resource statements at the head to a single load_and_authorize_resource statement with no arguments. I don't think there would be a problem with doing this, but I suppose that depends on the security behind #category.
I have this set up in my ActivitiesController:
class ActivitiesController < ApplicationController
def index
following_ids = current_member.following_members.map(&:id)
#activities = Activity.where("member_id in (?)", following_ids.push(current_member.id)).order("created_at desc")
end
end
This set up in my FollowsController:
def create
#member = Member.find_by_user_name(params[:member_id])
#follow_member = current_member.follow(#member)
if #follow_member
current_member.create_activity(#follow_member, 'followed')
respond_to do |format|
format.html { redirect_to #member }
format.js
end
end
end
And this set up to display the activity of following another member:
<div>
<span class="status_name">
<%= link_to activity.member.user_name, profile_path(activity.member) %>
</span>
<span>
is now following <%= link_to activity.targetable.following_member.user_name, "#" %>
</span>
<span class="meta">
<%= time_ago_in_words(activity.targetable.created_at) %>
</span>
</div>
<div class="act_content">
<%= follow_profile_link activity.targetable.following_member %>
</div>
I was able to get the following action to create a new activity item in the feed just fine but I can't figure out how to call to the member who's being followed. I get this error:
undefined method `following_member' for #<Follow:0x835b150>
app/views/activities/follow/_followed.html.erb:3:in `_app_views_activities_follow__followed_html_erb__269116874_68857716'
app/views/activities/index.html.erb:14:in `block in _app_views_activities_index_html_erb___16061925_44845644'
app/views/activities/index.html.erb:5:in `_app_views_activities_index_html_erb___16061925_44845644'
I can't figure out what I need to do or what specifically to call to make this work. Any ideas?
EDIT - Models
Activity Model
class Activity < ActiveRecord::Base
belongs_to :member
belongs_to :targetable, polymorphic: true
end
Follow Model
class Follow < ActiveRecord::Base
extend ActsAsFollower::FollowerLib
extend ActsAsFollower::FollowScopes
# NOTE: Follows belong to the "followable" interface, and also to followers
belongs_to :followable, :polymorphic => true
belongs_to :follower, :polymorphic => true
def block!
self.update_attribute(:blocked, true)
end
end
Member Model
class Member < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :email_confirmation, :password, :password_confirmation, :remember_me,
:first_name, :last_name, :user_name, :pursuits, :avatar, :bio, :city, :state, :country, :pursuit_list
has_many :medium
has_many :statuses
has_many :activities
acts_as_follower
acts_as_followable
acts_as_ordered_taggable
acts_as_ordered_taggable_on :pursuits
def create_activity(item, action)
activity = activities.new
activity.targetable = item
activity.action = action
activity.save
activity
end
Edit - Activities Migration
class CreateActivities < ActiveRecord::Migration
def change
create_table :activities do |t|
t.integer :member_id
t.string :action
t.integer :targetable_id
t.string :targetable_type
t.timestamps
end
add_index :activities, :member_id
add_index :activities, [:targetable_id, :targetable_type]
end
end
Activity Index
<% #activities.each do |activity| %>
<div class="status">
<div class="row">
<div class="span1 stream_av">
<%= avatar_profile_link activity.member %>
</div>
<div class="span7">
<%= render partial: "activities/#{activity.targetable_type.underscore}/#{activity.action}",
locals: { activity: activity } %>
</div>
</div>
</div>
<% end %>
New activity for uploading media
<div>
<span class="status_name">
<%= link_to activity.member.user_name, profile_path(activity.member) %></span> <span>uploaded new <%= link_to "Media", profile_media_path(activity.member) %></span> <span class="meta"> <%= time_ago_in_words(activity.targetable.created_at) %>
</span>
</div>
<div class="act_content">
<%= link_to image_tag(activity.targetable.asset.url(:medium), class: ''), medium_path(activity.targetable_id) %>
</div>
New activity for writing a status
<div>
<span class="status_name">
<%= link_to activity.member.user_name, profile_path(activity.member) %></span> <span>wrote a <%= link_to "Post", profile_stream_path(activity.member) %></span> <span class="meta"> <%= time_ago_in_words(activity.targetable.created_at) %>
</span>
</div>
<div class="act_content">
<%= activity.targetable.content %>
</div>
following_member returns an ActiveRecord object. So, you gotta do something like:
activity.targetable.following_member.first.user_name
instead of
activity.targetable.following_member.user_name
If you want to retrieve all the following members, you'll have to iterate through it.
<%activity.targetable.following_member.each do |member| %>
<%=member.user_name%>
<%end%>
I want to query multiple tables. For example in posts table there is a user_id linked to users id. While showing every post, I also want to display the picture of the user. My approach is this, but there is a problem. #user.picture method is undefined.
<% #programs.each do |post| %>
<%= #user = User.where("id = post.user_id") %>
<li class="one-third column">
<div class="wrapper">
<div class="postThumb"><img src="<%= #user.picture %>" /></div>
<div class="postDetails">
<%= link_to "#{ post.title.upcase! }".html_safe, all_posts_path, :class => "postTitle" %>
<p><%= truncate post.details, :length => 90 %></p>
</div>
</div>
</li>
<% end %>
Program Controller:
class ProgramController < ApplicationController
def index
#programs = Program.all
end
User model:
class User < ActiveRecord::Base
attr_accessible :password, :username, :oauth_token, :provider, :uid, :oauth_expires_at, :picture, :email, :name, :location, :gender, :updated_at, :is_admin
has_many :posts
has_one :program
has_many :programdetails, :through => :program
end
Program model:
class Program < ActiveRecord::Base
attr_accessible :details, :title, :user_id
belongs_to :user
has_many :programdetails
end
Try this instead, in the controller:
#programs = Program.includes(:user) # this will return all programs and related users in
# 2 database queries rather than N+1 queries
Then in the view:
<div class="postThumb"><img src="<%= post.user.picture %>" /></div>
Also, you can use image_tag instead.
Finally, you can probably change your post title link to:
<%= link_to post.title.upcase, all_posts_path, :class => "postTitle" %>
#user = post.user. Rails association will give back the associated user by itself.
And to correct above, syntactically, #user = User.find(post.user_id)
try changing this: #user = User.where("id = post.user_id")
into this: #user = User.where(id: post.user_id).first
or even better: #user = post.user as suggested by kiddorails
There is a much easier way to do this using the relations you have already defined:
Programs Controller
def index
#programs = Program.
includes(:user). # eager load user relation to avoid n+1
all
end
View
<% #programs.each do |post| %>
<li class="one-third column">
<div class="wrapper">
<div class="postThumb"><img src="<%= post.user.picture %>" /></div>
<div class="postDetails">
<%= link_to "#{ post.title.upcase! }".html_safe, all_posts_path, :class => "postTitle" %>
<p><%= truncate post.details, :length => 90 %></p>
</div>
</div>
</li>
<% end %>