NoMethodError in Refinery::Blog::Posts#index - ruby-on-rails

When I want to go to "localhost:3000/blog" the web page gives this error...
Showing C:/Sites/ifurniture/app/views/refinery/blog/posts/index.html.erb where line #3 raised:
undefined method `to_sym' for {:title=>"Body", :slug=>"body"}:Hash
Rails.root: C:/Sites/ifurniture
this is the blog controller..
module Refinery
module Blog
class PostsController < BlogController
before_filter :find_all_blog_posts, :except => [:archive]
before_filter :find_blog_post, :only => [:show, :comment, :update_nav]
before_filter :find_tags
respond_to :html, :js, :rss
def index
if request.format.rss?
#posts = if params["max_results"].present?
# limit rss feed for services (like feedburner) who have max size
Post.recent(params["max_results"])
else
Post.newest_first.live.includes(:comments, :categories)
end
end
respond_with (#posts) do |format|
format.html
format.rss { render :layout => false }
end
end
def show
#comment = Comment.new
#canonical = refinery.url_for(:locale => Refinery::I18n.current_frontend_locale) if canonical?
#post.increment!(:access_count, 1)
respond_with (#post) do |format|
format.html { present(#post) }
format.js { render :partial => 'post', :layout => false }
end
end
def comment
#comment = #post.comments.create(comment_params)
if #comment.valid?
if Comment::Moderation.enabled? or #comment.ham?
begin
CommentMailer.notification(#comment, request).deliver_now
rescue
logger.warn "There was an error delivering a blog comment notification.\n#{$!}\n"
end
end
if Comment::Moderation.enabled?
flash[:notice] = t('thank_you_moderated', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id])
else
flash[:notice] = t('thank_you', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id],
:anchor => "comment-#{#comment.to_param}")
end
else
render :show
end
end
def archive
if params[:month].present?
date = "#{params[:month]}/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%B %Y')
#posts = Post.live.by_month(archive_date).page(params[:page])
else
date = "01/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%Y')
#posts = Post.live.by_year(archive_date).page(params[:page])
end
respond_with (#posts)
end
def tagged
#tag = ActsAsTaggableOn::Tag.find(params[:tag_id])
#tag_name = #tag.name
#posts = Post.live.tagged_with(#tag_name).page(params[:page])
end
private
def comment_params
params.require(:comment).permit(:name, :email, :message)
end
protected
def canonical?
Refinery::I18n.default_frontend_locale != Refinery::I18n.current_frontend_locale
end
end
end
end
the post controller...
module Refinery
module Blog
class PostsController < BlogController
before_filter :find_all_blog_posts, :except => [:archive]
before_filter :find_blog_post, :only => [:show, :comment, :update_nav]
before_filter :find_tags
respond_to :html, :js, :rss
def index
if request.format.rss?
#posts = if params["max_results"].present?
# limit rss feed for services (like feedburner) who have max size
Post.recent(params["max_results"])
else
Post.newest_first.live.includes(:comments, :categories)
end
end
respond_with (#posts) do |format|
format.html
format.rss { render :layout => false }
end
end
def show
#comment = Comment.new
#canonical = refinery.url_for(:locale => Refinery::I18n.current_frontend_locale) if canonical?
#post.increment!(:access_count, 1)
respond_with (#post) do |format|
format.html { present(#post) }
format.js { render :partial => 'post', :layout => false }
end
end
def comment
#comment = #post.comments.create(comment_params)
if #comment.valid?
if Comment::Moderation.enabled? or #comment.ham?
begin
CommentMailer.notification(#comment, request).deliver_now
rescue
logger.warn "There was an error delivering a blog comment notification.\n#{$!}\n"
end
end
if Comment::Moderation.enabled?
flash[:notice] = t('thank_you_moderated', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id])
else
flash[:notice] = t('thank_you', :scope => 'refinery.blog.posts.comments')
redirect_to refinery.blog_post_url(params[:id],
:anchor => "comment-#{#comment.to_param}")
end
else
render :show
end
end
def archive
if params[:month].present?
date = "#{params[:month]}/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%B %Y')
#posts = Post.live.by_month(archive_date).page(params[:page])
else
date = "01/#{params[:year]}"
archive_date = Time.parse(date)
#date_title = ::I18n.l(archive_date, :format => '%Y')
#posts = Post.live.by_year(archive_date).page(params[:page])
end
respond_with (#posts)
end
def tagged
#tag = ActsAsTaggableOn::Tag.find(params[:tag_id])
#tag_name = #tag.name
#posts = Post.live.tagged_with(#tag_name).page(params[:page])
end
private
def comment_params
params.require(:comment).permit(:name, :email, :message)
end
protected
def canonical?
Refinery::I18n.default_frontend_locale != Refinery::I18n.current_frontend_locale
end
end
end
end
and this is the index.html.erb of Blog.
<section class="container">
<% content_for :body do %>
<%= raw #page.content_for(Refinery::Pages.default_parts.first.to_sym) if Refinery::Pages.default_parts.any? %>
<% if #posts.any? %>
<section id="blog_posts" class="news">
<%= render :partial => "/refinery/blog/shared/post", :collection => #posts %>
<%= will_paginate #posts %>
</section>
<% else %>
<p><%= t('.no_blog_articles_yet') %></p>
<% end %>
<% end %>
<% content_for :side_body_prepend do -%>
<%= raw #page.content_for(Refinery::Pages.default_parts.second.to_sym) %>
<% end if Refinery::Pages.default_parts.many? -%>
<%= render "/refinery/content_page" %>
<% content_for :stylesheets, stylesheet_link_tag('refinery/blog/frontend') %>
</section>
I'll be watching for your help, thanks.

You can use to_sym method on hash or string so in your code you can do something like this:
index.html
instead this:
<%= raw #page.content_for(Refinery::Pages.default_parts.first.to_sym) if Refinery::Pages.default_parts.any? %>
put this:
<%= raw #page.content_for(Refinery::Pages.default_parts.first[:title].to_sym) if Refinery::Pages.default_parts.any? %>
instead [:title]you can also use [:slug]

Related

Rails, after remote delete of item I get: First argument in form cannot contain nil or be empty

I want to delete an image on click.
This is in my view
<%=form_for #area, url: areas_update_path, remote: true, html: {class: "form-horizontal",:multipart => true} do |f|%>
....
<% #area.area_attachments.each do |a| %>
<%unless a.image.blank?%>
<%= link_to delete_area_attachment_path(a), :remote => true, :method => :delete do%>
<%= image_tag a.image_url(:thumb), class:"delete-image" %>
<% end %>
<% end %>
<% end %>
....
<% end %>
After I click on an image, the image gets deleted, but I get
First argument in form cannot contain nil or be empty
In the first line of the code that I posted (#area I guess)
My delete_area_attachment method in my area_attachments_controller
def delete_area_attachment
#areaAttachment = AreaAttachment.find(params[:id])
#areaAttachment.destroy
respond_to do |format|
format.js
end
end
I guess the #area variable has to be initialized, but why?
What I am trying to delete is an area_attachment not an area, and I already initialized it, so what does the #area variable has to do with that?
How do I go about it here?
EDIT:
my relative routes:
#Area Paths
get '/areas/new', to: 'areas#new', :as => 'areas_new'
post '/areas/create', to: 'areas#create', :as => 'areas_create'
get '/areas/:id/destroy', to: 'areas#destroy', :as => 'areas_destroy'
delete 'delete_area/:id', controller: 'areas', action: 'delete_area'
get '/areas/:id/edit', to: 'areas#edit', :as => 'areas_edit'
patch '/areas/:id/update', to: 'areas#update', :as => 'areas_update'
#Area Attachment Paths
delete 'delete_area_attachment/:id', controller: 'area_attachments', action: 'delete_area_attachment', :as => 'delete_area_attachment'
My areas_controller
class AreasController < ApplicationController
before_action :set_areas
before_action :set_area, only: [:edit, :delete, :update, :destroy]
def new
#area = Area.new
#languages = Language.all
#area_attachment = #area.area_attachments.build
end
def create
#area = Area.new(area_params)
if #area.save && manage_strings
params[:area_attachments]['image'].each do |a|
#area_attachment = #area.area_attachments.create!(:image => a, :area_id => #area.id)
end
#status = 'success'
else
#status = 'error'
#errormessages = #area.errors.full_messages
end
respond_to do |format|
format.js
end
end
def edit
end
def update
if #area.update(area_params) && manage_strings
params[:area_attachments]['image'].each do |a|
#area_attachment = #area.area_attachments.create!(:image => a, :area_id => #area.id)
end
#status = 'success'
else
#status = 'error'
#errormessages = #area.errors.full_messages
end
respond_to do |format|
format.js
end
end
def delete_area
#area = Area.find(params[:id])
#area.destroy
respond_to do |format|
format.js
end
end
def find_area_by_id
area = Area.find(params[:id])
render json: area
end
protected
def news_list
respond_to do |format|
format.js
end
end
private
def area_params
params.require(:area).permit(:id, area_attachments_attributes: [:id, :area_id, :image])
end
def set_area
#area = Area.find_by_id(params[:id])
#languages = Language.all
#area_attachments = #area.area_attachments.all
end
def set_areas
#areas = Area.all
end
def manage_strings
if params[:area][:strings].any?
params[:area][:strings].each do |key,value|
string = #area.article_localizations.find_or_initialize_by(:language_id => key.to_i)
string.title = params[:area][:strings][key][:title]
string.text = params[:area][:strings][key][:text]
string.save
end
end
end
end
In delete_area_attachment before #areaAttachment.destroy add:
#area = Area.find_by_id(#areaAttachment.area_id)

Rails Ajax render partial with local variable

Hey I am trying to render a partial using ajax everything work in rails normal form but when I am rendering a partial using ajax local variables don't work I am trying to create a like and dislike system for that I have created a model called FeedLike here I can like and dislike using simple create and destroy but when I am using ajax and there I am calling this action below :
$('#feed_like').html("<%= j render :partial => 'shared/dislike', :locals => { feed: #feed= #feed} %>");
I am getting the error No route matches
{:action=>"destroy", :controller=>"feed_likes", :feed_id=>nil, :user_id=>1}
And my dislike link is like this it is a partial which is under :
<div id="feed_dislike">
<%= link_to "Dislike",{ :action => 'destroy', :controller => 'feed_likes', :feed_id => #feed, :user_id => current_user.id }, class: "btn btn-primary" %>
</div>
everything work fine when I am not using ajax but when I am rendering partial why #feed is not getting any value what am I supposed to do . To get the value of feed.id . feed.id is coming from and model called Feed and it is under look and there I am rendering these two forms using partials .
now I am pasting some codes which will give you what I am doing :
#shared/_feed.html.erb
<% if #feed_items.try(:any?) %>
<ol class="microposts">
<%= render #feed_items %>
</ol>
<%= will_paginate #feed_items %>
<% end %>
And #feed_items is coming from :
#feeds/_feed.html.erb
<li id="feed-<%= feed.id %>">
<%= image_tag(current_user.avatar.url(:thumb), :size => '50x50') %>
<span class="user"><%= link_to feed.user.name, feed.user %></span>
<span class="content"><%= feed.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed.created_at) %> ago.
</span>
<% #like =FeedLike.where(:user_id => "#{current_user.id}", :feed_id => "#{feed.id}")
%>
<%= render :partial => 'shared/feed_like', locals: { feed: #feed= feed.id} %>
</li>
And now feed_like partial :
#shared/_feed_like.html.erb
<% if #like.count == 0 %>
<%= render :partial => 'shared/like', locals: { feed1: #feed= #feed} %>
<% else %>
<%= render :partial => 'shared/dislike', locals: { feed: #feed} %>
<% end %>
Controllers code for :
class FeedsController < ApplicationController
before_action :authenticate_user! ,only: [:create, :destroy]
def create
#feed = current_user.feeds.build(feed_params)
#feed_likes = FeedLike.new
if #feed.save
#redirect_to root_url
respond_to do |format|
format.html { redirect_to root_url }
format.js
end
else
respond_to do |format|
format.html { redirect_to root_url }
format.js { render :js=>'alert("you can not leave post empty");' }
end
end
end
def destroy
end
private
def feed_params
params.require(:feed).permit(:content)
end
end
FeedsLike controller :
class FeedLikesController < ApplicationController
before_action :authenticate_user! ,only: [:create, :destroy]
def index
#fees = FeedLike.all
respond_to do |format|
format.html
format.js
end
end
def update
#feed_likes = FeedLike.find_or_create_by(feed_like_params)
respond_to do |format|
if #feed_likes.save
format.html { redirect_to root_url, notice: 'Like ' }
else
end
end
end
def create
#feed_likes = FeedLike.find_or_create_by(:feed_id => params[:feed_id],:user_id =>params[:user_id])
respond_to do |format|
if #feed_likes.save
format.html { redirect_to root_url, notice: 'Like ' }
format.js
else
end
end
end
def delete
end
def destroy
#feed_likes = FeedLike.where(:feed_id => params[:feed_id],:user_id =>params[:user_id])
respond_to do |format|
if #feed_likes.destroy_all
format.html { redirect_to root_url, notice: 'Unlike ' }
else
end
end
end
def feed_like_params
params.require(:feed_like).permit(:user_id, :feed_id)
#params[:market_place]
end
end
And staticpage controller :
class StaticPagesController < ApplicationController
before_action :authenticate_user!
def home
if user_signed_in?
#feed_likes = current_user.feed_likes.new
#feed = current_user.feeds.build
#feed_items = current_user.feed.paginate(page: params[:page])
# #likes = Feed.find(:all,
# :select => '"feeds".id, "feeds".content, count("feed_likes".id) as Like',
# :from => :feeds,
# :left_join => '"feed_likes"',
# :on => '"feeds".id = "feed_likes"."feed".id',
# :limit => 5
# )
# #like =Feed.find_by_sql "
# SELECT id
# FROM feed_likes
# WHERE user_id = #{current_user.id}
# AND feed_id =#{feed.id}
# LIMIT 0 , 30
# "
end
end
def help
end
def about
end
def contact
end
end
your feed is nil which is why it is crashing
please add this in your feed_likes controller.
before_action :get_feed ,only: [:create, :destroy]
and at the bottom add this method
def get_feed
#feed= Feed.find(params[:feed_id])
end
Your feed definition looks wrong in your javascript file. Try this instead:
$('#feed_like').html("<%= j render :partial => 'shared/dislike', :locals => { feed: #feed} %>");

formal argument cannot be an instance variable?

<% #idea.each do |#idea| %>
<div id="basic_details" class="idea-show-columns">
<%= render :partial => '/ideas/idea_basic_show', :locals => {:idea => #idea} %>
<%= render :partial => 'ideas/comments' %>
<%= render :partial => 'ideas/mockups' %>
</div>
<div id="copy_details" class="idea-show-columns">
<%= render :partial => 'ideas/ copy_show', :locals => {:idea => #idea} %>
</div>
<% end %>
When I take the # off it says "Parameter 'idea' is not used", I cannot find the proper syntax for this.
IdeasController
class IdeasController < ApplicationController
def index
respond_to do |format|
if request.xhr?
#ideas = Idea.select("sku, id").order(:sku)
else
if params[:search]
#ideas = Idea.where("sku like '%#{params[:search]}%' or working_name like '%#
{params[:search]}%' or product_name like '%#{params[:search]}%'").paginate(:page =>
params[:page]).reload
else
#ideas = Idea.paginate(:page => params[:page]).reload
end
end
format.html
format.json {render json: #ideas.where("sku like ?", "%#{params[:q]}%") }
end
end
def show
#idea = Idea.find_by_permalink(params[:id])
end
def new
#idea = Idea.new
end
def create
#idea = Idea.new(new_idea_params)
if #idea.save
flash[:notice] = 'Idea created!'
redirect_to ideas_url
else
render :new
end
end
def edit
#idea = Idea.find_by_permalink(params[:id])
end
def update
#idea = Idea.find_by_permalink(params[:id])
if request.xhr?
if params[:comment]
#idea.comments.create(:title => params[:comment][:title], :comment => params[:comment][:comment], :user_id => current_user.id)
end
if #idea.update_attributes(update_status_params)
#success = true
else
#success = false
end
else
if #idea.update_attributes(edit_idea_params)
flash[:notice] = 'Idea updated!'
redirect_to idea_url(params[:id])
else
render :edit
end
end
end
def destroy
Idea.find_by_permalink(params[:id]).destroy
flash[:success] = "Idea destroyed."
redirect_to ideas_url
end
def generate_mockups
idea = Idea.find_by_permalink(params[:id])
begin
idea.generate_mockups
rescue Exception => e
flash[:error] = "There was an error generating the mockups for #{idea.working_name}! # {e.message}"
end
flash[:notice] = "Successfully generated mockups for #{idea.working_name}"
redirect_to idea_url(params[:id])
end
def signoff
if current_user.has_overlord_access?
if params[:idea_id]
idea = Idea.find(params[:idea_id])
idea.overlord_id = current_user.id
idea.status = 'Ready To Publish'
idea.save
flash[:notice] = "#{current_user.full_name} just signed off on #{idea.sku}"
redirect_to :action => :signoff
end
#ideas = Idea.awaiting_overlord_signoff.reload
#idea = #ideas.first.reload
else
flash[:notice] = 'Sorry, you must have overlord access to sign off on ideas.'
redirect_to ideas_path
end
end
private
def new_idea_params
params.require(:idea).permit(:sku, :working_name, :working_description, :priority)
end
def update_status_params
params.require(:idea).permit(:art_status, :copy_status)
end
def edit_idea_params
(params[:idea][:color_ids] ||= []) unless !current_user.has_artist_access?
(params[:idea][:imprintable_ids] ||= []) unless !current_user.has_copywriter_access?
(params[:idea][:stores_ids] ||= []) unless !current_user.has_copywriter_access?
(params[:idea][:taxonomies_ids] ||= []) unless !current_user.has_copywriter_access?
params.require(:idea).permit(:sku, :working_name, :working_description, :priority,
:product_name, :product_line_tokens,
:description, :meta_description, :meta_keywords, :artist_id,
:copywriter_id, :overlord_id,
{:store_ids => []}, {:taxonomy_ids => []}, :base_price,
:shipping_category, :default_artwork_id,
:tax_category, {:imprintable_ids => []}, :marketplace,
:product_type,
:base, :colors_offered, :special_instructions, :copy_status,
:art_status, {:color_ids => []},
:artworks_attributes => [:height, :width, :from_top,
:from_center, :idea_id, :dimensions, :file, :_destroy, :id])
end
def update_status_params
params.require(:idea).permit(:copy_status, :art_status)
end
end
I am getting the error
undefined method `each' for nil:NilClass
It should :
<% unless #ideas.nil? %>
<% #ideas.each do |idea| %>
<div id="basic_details" class="idea-show-columns">
<%= render :partial => '/ideas/idea_basic_show', :locals => {:idea => idea} %>
<%= render :partial => 'ideas/comments' %>
<%= render :partial => 'ideas/mockups' %>
</div>
<div id="copy_details" class="idea-show-columns">
<%= render :partial => 'ideas/ copy_show', :locals => {:idea => idea} %>
</div>
<% end %>
<% end %>
Few things:
if you need to use #ideas in show view you need to load them using before_filter
dont do this dea.where("sku like '%#{params[:search]}%' because this is not secure. Do something like where("code = ?", params[:code])

Albums in rails

I would like to create an image gallery in rails. I have produced a setup that allows you to create an album and upload photos to it. However, I am stumped on how I could allow the user to set one of the existing images as the album cover in the image's index view.
Anyone have some ideas? I found that if I used radio buttons, I couldn't figure hout how to determine which image was selected by ajax. I also don't know how I would force only one image being set as album cover.
Here is my setup:
Controller
class Admin::AlbumsController < ApplicationController
respond_to :html, :json
def index
#albums = Album.all
end
def new
#album = Album.new
end
def create
#album = Album.new(params[:album])
if #album.save
flash[:notice] = "Successfully created album!"
redirect_to [:admin, :albums]
else
render "new"
end
end
def edit
#album = Album.find(params[:id])
end
def show
#album = Album.find(params[:id])
end
def update
#album = Album.find(params[:id])
#album.update_attributes(params[:album])
if #album.update_attributes(params[:album])
respond_with #album
flash[:notice] = "Successfully updated Album"
else
render "edit"
end
end
def destroy
#album = Album.find(params[:id])
#album.destroy
#id = #album.id
FileUtils.remove_dir("#{Rails.root}/public/uploads/image/picture/#{#id}", :force => true)
respond_to do |format|
format.js { render :layout => false }
end
redirect_to admin_albums_path
end
def random_image
#image_files = %w( .jpg .gif .png )
#files ||= Dir.entries(
"#{RAILS_ROOT}/public/uploads").delete_if { |x|
!#image_files.index(x[-4,4])
}
file = #files[rand(#files.length)];
#files.delete file
return "/images/logos/#{file}"
end
def ajaxUpdate
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:albumcover])
if #image.update_attributes(params[:image])
flash[:notice] = "Successfully updated Image"
else
render "edit"
end
end
end
class Admin::ImagesController < ApplicationController
respond_to :html, :json
#before_filter :split_hash, :only => [ :create, :update ]
def index
#album = Album.find(params[:album_id])
#images = #album.images.all
end
def new
#album = Album.find(params[:album_id])
#image = #album.images.new
end
def create
params[:image][:source].each do |image|
#album = Album.find(params[:album_id])
#params = {}
#params['source'] = image
#image = #album.images.create(#params)
end
if #image.save
if params[:image][:source].size > 1
flash[:notice] = "Successfully added images!"
else
flash[:notice] = "Successfully added image!"
end
redirect_to [:admin, #album, :images]
else
render "new"
flash[:notice] = "Did not successfully add image :("
end
end
def show
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:id])
end
def edit
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:id])
end
def update
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:id])
if #image.update_attributes(params[:image])
redirect_to [:admin, #album, :images]
flash[:notice] = "Successfully updated Image"
else
render "edit"
end
end
def destroy
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:id])
#image.destroy
#albumid = #album.id
#id = #image.id
FileUtils.remove_dir("#{Rails.root}/public/uploads/image/picture/#{#albumid}/#{#id}", :force => true)
redirect_to admin_album_images_path(#album)
end
def ajaxUpdate
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:albumcover])
if #image.update_attributes(params[:image])
flash[:notice] = "Successfully updated Image"
else
render "edit"
end
end
# def split_hash
# #album = Album.find(params[:album_id])
# #image = #album.images
# array_of_pictures = params[:image][:picture]
# array_of_pictures.each do |pic|
# size = array_of_pictures.size.to_i
# size.times {#image.build(params[:image], :picture => pic)}
# #image.save
# end
# end
end
Models
class Album < ActiveRecord::Base
attr_accessible :title, :description, :album_id
has_many :images, :dependent => :destroy
validates :title, :description, :presence => true
end
class Image < ActiveRecord::Base
attr_accessible :title, :description, :source, :album_id, :albumcover, :image, :image_id
belongs_to :album
accepts_nested_attributes_for :album
mount_uploader :source, PictureUploader
end
View
<% content_for :head do %>
<%= stylesheet_link_tag 'admin/images' %>
<%= javascript_include_tag "admin.js" %>
<% end %>
<% content_for :menu do %>
<li class="menu_item"><%=link_to "New Album", :controller => "albums", :action => "new" %></li>
<li class="menu_item"><%= link_to "Add Images", {:controller => "images", :action => "new"}, :class => "highlight_menu"%> </li>
<% end %>
<%= link_to "< Back", admin_albums_path, :id => "return_link" %> </br>
<h1 class="section-title"> <strong style="font-weight: 600;"><%=best_in_place [:admin,#album], :title, :ok_button => :confirm %></strong></h1>
<h4 class="album-desc"><%= best_in_place [:admin,#album], :description, :type => :textarea, :ok_button => :confirm%></h4>
<%= form_tag admin_album_images_path(#album) do %>
<% if !#images.blank? %>
<% #images.each do |image| %>
<div class="item">
<div class="image-box">
<div class="source">
<%= image_tag image.source %>
</div>
</div>
<div class="info">
<div class="item-links">
<%= link_to "Edit", edit_admin_album_image_path(#album, image.id), :id => "edit"%>
<%= link_to "Delete",
admin_album_image_path(#album, image.id),
:class => "item-link delete-image",
:method => :delete,
:remote => true,
:confirm => "Are you sure?" %>
</div>
</div>
</div>
<% end %>
<% else %>
<p class="alert">No images in this album</p>
<% end %>
<% end %>
Answer!
*albums_controller*
def albumCoverSet
#album = Album.find(params[:album_id])
#image = #album.images.find(params[:albumcover])
if #image.update_attributes(params[:image])
flash[:notice] = "Successfully updated Image"
else
render "edit"
end
end
* album view *
<div class="image">
<%= image_tag album.images.find(album.albumcover_id).source, :class => "image" %>
</div>
model
class Album < ActiveRecord::Base
attr_accessible :title, :description, :album_id, :albumcover_id
has_many :images, :dependent => :destroy
has_one :albumcover, :class_name => "Image"
validates :title, :description, :presence => true
end
You can add a 'primary_image_id' to the Album in a migration.
has_one :primary_image, :class_name => 'Image'
In your form, you can show all album.images and select one. Radio buttons should work just fine.
Submitting the value of the param would set the primary_image_id.

Confused as to which Prototype helper to use (updated)

This is a continuation of Confused as to which Prototype helper to use. My code has been updated to reflect other user's suggestions:
(model) message.rb:
class Message < ActiveRecord::Base
after_create :destroy_old_messages
def old_messages
messages = Message.all(:order => 'updated_at DESC')
if messages.size >= 24
return messages[24..-1]
else
return []
end
end
protected # works without protected
def destroy_old_messages
messages = Message.all(:order => 'updated_at DESC')
messages[24..-1].each {|p| p.destroy } if messages.size >= 24
end
end
(view) index.html.erb:
<div id="messages">
<%= render :partial => #messages %>
</div>
<%= render :partial => "message_form" %>
(view) _message.html.erb:
<% div_for message do %>
<%= h message.created_at.strftime("%X") %> - <%= h message.author %><%= h message.message %>
<% end %>
(view) _message_form.html.erb:
<% remote_form_for :message, :url => { :action => "create" }, :html => { :id => 'message_form'} do |f| %>
<%= f.text_area :message, :size => "44x3" %><br />
<%= submit_to_remote 'submit_btn', 'submit', :url => { :action => 'create' } %><br />
<% end %>
(view) create.rjs:
page.insert_html :top, :messages, :partial => #message
page[#message].visual_effect :grow
page[:message_form].reset
flash[:notice]
flash.discard
# #old_messages.each do |m|
# page.remove(m.id)
# end
(controller) messages_controller.rb:
class MessagesController < ApplicationController
def index
#messages = Message.all(:order => "created_at DESC")
respond_to do |format|
format.html
format.js
end
end
def new
#message = Message.new
respond_to do |format|
format.html
end
end
def create
#message = Message.new(params[:message])
# #old_messages = Message.old_messages
respond_to do |format|
if #message.save
flash[:notice] = 'message created.'
format.html { redirect_to(messages_url) }
format.js
else
format.html { render :action => "new" }
end
end
end
def update
#message = Message.find(params[:id])
respond_to do |format|
if #message.update_attributes(params[:message])
flash[:notice] = 'message updated.'
format.html { redirect_to(messages_url) }
format.js
else
format.html { render :action => "edit" }
end
end
end
def destroy
#message = Message.find(params[:id])
#message.destroy
respond_to do |format|
format.html { redirect_to(messages_url) }
format.js
end
end
end
With the exception of the old_messages method in the model, all of the commented code were recommended changes from the previous post to make this work. But as soon as I uncomment the last three lines from create.rjs and #old_messages = Message.old_messages from the controller, I can't even submit messages with the message_form partial. Can anyone see what's wrong here? I'm just trying to create a basic app to help further my understanding of rails and rjs. I would greatly appreciate any suggestions or corrections you have to share, thank you for reading my post.
it's not what you're asking for, but i have a suggestion...
to get the older messages you can use named_scope.
in your case, (if i understood what you want) i think it would be something like:
# model
named_scope :limit, lambda { |num| { :limit => num } }
named_scope :order, lambda { |ord| { :order => ord } }
and
#controller
Message.order("updated_at DESC").limit(24)
the problem is that old_messages is an instance method, and you're calling from a class.
if you do
def self.old_messages
# ...
end
it's now a class method.
this blog has a good explanation about class and instance methods.

Resources