Polymorphic association gone bad? - ruby-on-rails

I am working on a self-learning project for learning Rails that can be found on github here. (The latest commit includes this error)
However I am posting here all codes:
Model: photo_post.rb
class PhotoPost < ActiveRecord::Base
belongs_to :user
has_attached_file :image, styles: {
post: "200x200>"
}
end
Controller: PostsController
class PostsController < ApplicationController
def show
#post = Post.find(params[:id])
end
end
Controller: PhotoPostsController
class PhotoPostsController < ApplicationController
def create
content = build_content
post = current_user.posts.build(content: content)
if post.save
redirect_to root_path
else
flash.alert = "Please enter a title"
redirect_to root_path
end
end
private
def build_content
PhotoPost.new(photo_post_parameters)
end
def photo_post_parameters
params.require(:photo_post).permit(:image)
end
end
_post.html.erb
<%= div_for post do %>
<%= link_to post.user.username, post.user %>
suggested
<%= render post.content %>
<%= link_to time_ago_in_words(post.created_at), post %>
home_controller.rb
class HomeController < ApplicationController
protect_from_forgery
def show
#title_post = TitlePost.new
#photo_post = PhotoPost.new
#posts = current_user.posts
end
end
I created three models. Posts is the main one and TitlePosts and PhotoPosts are models under Posts.
The Title Posts work fine as I can submit a title.
For Photo Posts I used paperclip. However I try to upload an image I get the following error:
'nil' is not an ActiveModel-compatible object that returns a valid partial path.
You can also check the error on imageshack here.(Screenshot with better_errors).
I was going to copy the relevant codes and files but the full project can be found on github at the link I provided. If you need any further info please ask me.
Thank you.
Any help is greatly appreciated.

In just hitting the page current_user isn't defined, so current_user.posts is trying to get posts on a Nil object.
This cleared up the error, though it isn't going to correct your issues:
HomeController ~ line 7
#posts = []
if current_user
#posts = current_user.posts
end
You may also want to add something to your controller to require authentication so that current_user is set:
before_filter :authenticate_user!

OK this seems weird (to me). The error was caused by forgetting to install ImageMagick.
After installing it everything works fine.

Related

ruby/rails displaying database on index view

I've looked at all the other question on here and none seem to fully answer my question, as one solution ends up causeing another error somewhere else in my project.
I am trying to display all "Promotions" from the promotions database on the index view but I keep running into errors, my current error is that in my home controller its saying that "Couldn't find Promotion with 'id'=all".
Any help is greatly appreciated.
Home Controler
class HomeController < ApplicationController
def index
#Promotion = Promotion.find :all
end
Model
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
self.primary_key= :promo_id
end
View
<%= #promotions.promo_id %>
If you want to show all your Promotion, do something like
def index
#promotions = Promotion.all
end
And in your view:
<% #promotions.each do |promotion| %>
<%= promotion.id %>
<%= promotion.name %>
<% end %>

Tracking and displaying likes using public activity

I have been trying to figure out how to make it so that I can create an activity page that lists out likes by other users on your OWN individual posts. In my case, I have no friend or following system so literally anyone who signs up can like a post. I have been looking everywhere and cannot find an example of how it is done
Currently, I have defined a like method in my post controller
def like
#post = Post.find(params[:id])
#post.upvote_by current_user
redirect_to :back
end
I also have an activities controller:
class ActivitiesController < ApplicationController
def index
#activities = PublicActivity::Activity.where(trackable_type: "Post", trackable_id: current_user.post_ids, key: "post.like")
end
end
My Post model looks like this:
class Post < ActiveRecord::Base
belongs_to :user
acts_as_votable
include PublicActivity::Model
tracked only: [:create, :like], owner: Proc.new{ |controller, model| model.user }
default_scope -> { order('created_at DESC') }
end
My activities view template looks like this:
<% #activities.each do |activity| %>
<%= activity.inspect %>
<% end %>
As of right now, my notification page displays nothing. How do i go about displaying a feed showing all the likes that my posts received from other users. Thanks so much
When upvote_by is called on a post, an ActsAsVotable::Vote record is created. You therefore have to add public activity to this model if you want to log votes.
class ActsAsVotable::Vote
include PublicActivity::Model
tracked only: [:create], owner: Proc.new{ |controller, model| model.user }
end

form submit in rails not working, possible routing/path error unsure why?

I am trying to submit a form in rails that is just a pdf uplaod (using paperclip). There is something wrong with either my form, controller or model and i am not sure which.
this is my form:
<%= form_for #yearguide, :html => { :multipart => true } do |form| %>
<%= form.file_field :pdf %>
<%= form.submit "Add Event", class: "btn btn-primary" %>
<% end %>
my controller:
class YearController < ApplicationController
def new
#yearguide = Year.create(year_params)
end
def create
if #yearguide = Year.save
redirect_to '/'
else
render 'new'
end
end
my model:
class YearlyGuide < ActiveRecord::Base
has_attached_file :pdf
validates_attachment :document, content_type: { content_type: "application/pdf" }
end
my routes:
resources :year
I add the file and press upload, but I am being redirected to 'update.html.erb'.
The file doesn;t exist in the db, just an empty record.
When i debug the params on pressing uplaod I get this output
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"G7ZrXEiip/gsqhDObcfYhTT9kerYZGk+Zl29kWA5jos=", "year"=>{"pdf"=>#<ActionDispatch::Http::UploadedFile:0x000001029b0340 #tempfile=#<Tempfile:/var/folders/ns/ry6z7jfd6qg6j8xr2q6dw0yc0000gn/T/RackMultipart20140609-21455-1eg1sk3>, #original_filename="Artsmill Hebden Bridge Exhibition Programme 2014.pdf", #content_type="application/pdf", #headers="Content-Disposition: form-data; name=\"year[pdf]\"; filename=\"Artsmill Hebden Bridge Exhibition Programme 2014.pdf\"\r\nContent-Type: application/pdf\r\n">}, "commit"=>"Add Event", "action"=>"update", "controller"=>"year", "id"=>"9"}
=========================
EDIT
OK, so discrepancies with my naming led to the previosu errors, i started again, generating:
rails g model YearlyGuide pdf:attachment start:datetime end:datetime
rails g controller YearlyGuide new index show
now in my routes i have added
resources :yearly_guides
when i visit
/yearly_guides/new
I get this error
uninitialized constant YearlyGuidesController
I am really at a loss as to what I am doing wrong, I have done this before and never had these issues.
#iceman, thanks for your help and patience thus far.
The controller is not doing what it's supposed to do. This is the bare bones basic scheme of creating a new object in Rails.
class YearsController < ApplicationController
def new
#yearguide = Year.new
end
def create
#yearguide = Year.create(year_params)
if #yearguide.save
redirect_to '/' # I would consider redirect_to #yearguide to show the newly created object
else
render 'new'
end
end
end
EDIT:
You have to update your routes.rb to
resources :years
Since you are creating the yearguide object, rails infer that you have to do put/patch request, so request is going to update since rails getting id.
You have two options.
1) Change new method of controller like below
class YearController < ApplicationController
def new
#yearguide = Year.new
end
end
2) Override the method parameter by passing method params as 'post' inside your form tag

Display error from an associatd object Rails

I really don't know the way to display error on a view when we post datas which are associated from another model.
My needs :
I have a form displayed in app/view/libraries/show.html.erb
The comments are associated to library in my app. Means that for a library we can have one or many comments.
In model/comment.rb i put that :
validates :name, presence: true
in app/view/libraries/show.html.erb : i need to display error but don't know the way to retrieve it :
<% if #library.comment.errors.any? %>
<%= #library.comment.errors.count %>
<% end %>
CommentsController
class CommentsController < ApplicationController
def new
end
def create
#library= Library.find(params[:library_id])
#comment = #library.comments.create(params[:comment].permit(:name, :commenter))
redirect_to #library
end
end
This does not work someone can please explain to me the way it works ?? I am doing the guide rails getting start but want to add some features simple in it...
Thanks a lot guys !
If all you need is the count, you can put it in flash
def create
#library= Library.find(params[:library_id])
#comment = #library.comments.create(params[:comment].permit(:name, :commenter))
flash[:error_count] = #comment.errors.count
flash.keep[:error_count]
redirect_to #library
end
<% if flash[:error_count] > 0 %>
<%= flash[:error_count] %>
<% end %>

Trying to link to specfic new comic review page

I'm trying to get a link on an articles show page so that when a user clicks write new review it takes them to the link
/comic_reviews/'the article they want to comment on'/reviews/new
where they will be directed to the new reviews page
how can i accomplish this with
In your routes file you would specify a route like this
match '/comic_reviews/:comic_name/reviews/new' => 'reviews#new', via: :get
Then in your reviews controller you would need something like this
reviews_controller.rb
class ReviewsController < ApplicationController
def new
#comic = Commic.find_by_name(params[:comic_name])
if #comic
#review = #comic.reviews.build
render 'new'
else
#Render some error page since comic was not found
end
end
end
You will then have access to #comic and #review in your reviews/new view so you could build a form that just makes a post to create a review and allows you to store it. This should get you going.
Edit
In your new view you'd need to have a form that looks something like this
<%= form_for #review do |f| %>
<%= f.label :some_attribute %>:
<%= f.text_field :some_attribute %><br />
<%= f.submit %>
<% end %>
This will be expecting you have a route to create a review in your routes file and an action in your ReviewsController.
If you are struggling with such topics I suggest you read over this excellent tutorial
http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
Or just read through the documentation for Rails API which will give you pretty accurate examples.
You can do this via routes
resources :comic_reviews do
resources :reviews
#probably_some_other_route_here
end
And with restful pattern it will be easy to achieve whatever you want
controller
Someclass < Someotherclass
#some your code
def new
#instance_var = Your_model.new
end
def create
#instance_var = Your_model.new(params[:some_name_here])
if #instance_var.save
redirect_to somewhere
else
render 'new'
end
end
end
Also you'll need form, but i dont think that will cause any troubles

Resources