rails 3 custom date won't save - ruby-on-rails-3

I'm a complete rails noob, so there's probably something very simple I'm missing here. I have these little tweet-type things called microposts, and I want each micropost to have a release date set by the user. My form looks ok and doesn't show any errors in the browser when I create a new micropost, but the release date isn't being saved in the database. In my form to create a new micropost, I have this:
<div class="field">
<%= f.label :release_date %>
<%= f.text_field :release_date, :size => 10 %>
</div>
In my database schema, I have this:
create_table "microposts", :force => true do |t|
t.string "content"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.datetime "release_date"
end
I made the release_date attribute accessible in my Micropost model like so:
attr_accessible :content, :release_date
And my create method in my Micropost controller looks like this:
def create
#micropost = current_user.microposts.build(params[:micropost])
if #micropost.save
flash[:success] = "New event created."
redirect_to root_path
else
render 'pages/home'
end
end
Everything else saves just fine. It's only the release date that seems to be ignored. This is just a wild guess, but is rails ok with something like 10/25/2011 being saved as a datetime? Or is that supposed to be saved as a string and then parsed into a proper datetime format?

There's a lot of info missing here to evaluate. The params hash probably doesn't have the value, or it isn't hashed in a way expected by rails.
In your User model, do you have:
accepts_nested_attributes_for :microposts
Also, you'll want to look up tutorials on form_for and fields_for in rails.

Likely the format you are entering the date in isn't getting cast as a datetime properly:
def Micropost < ActiveRecord::Base
before_validation_on_create :convert_release_date_to_datetime
private
def convert_release_date_to_datetime
self.release_date = Time.parse(release_date)
end
end

Related

How to count all the likes that User has done on my specific items (Rails)

My apologies for the newbie question, I'm relatively new to Rails and SQL. I'm trying to count all the likes a User has done on my specific items. With the help of the SO community and from Treehouse Coding I am able to show which Users have liked my specific items. In addition, I was able to research how to show all the likes that I have received (from Lisa, James, Harry, etc.) using .join in my controller. Now I would like to show the count for each specific User. So for instance if James like 4 of my items I would like to show 4 next to James. I have listed all my relevant code below, thank you guys so much!!
Index.html.erb
My Fans - <%= #likersnumero%>
<%- #likers.each do |liker| %>
<%= image_tag liker.avatar, width: 25, class: "css-style" %>
<%= liker.username %>
<% end %>
Items_controller
def index
#items = Item.order("created_at DESC")
if current_user.present?
#likers = current_user.items.map(&:likes).flatten.map(&:user).flatten
#likersnumero = current_user.items.joins(:likes).map(&:user).count
end
end
Item.rb
class Item < ApplicationRecord
has_many :likes, :counter_cache => true
end
Users.rb
class User < ApplicationRecord
has_many :likes
def likes?(post)
post.likes.where(user_id: id).any?
end
#Tried using def total_likes in my index.html.erb using <%= liker.total_likes%>
but got the following
error SQLite3::SQLException: no such column: likes:
SELECT SUM(likes) FROM "likes" WHERE "likes"."user_id" = ?"
def total_likes
likes.sum(:likes)
end
end
Routes.rb
Rails.application.routes.draw do
resources :items do
resource :like, module: :items
end
root to: "items#index"
end
Schema.rb
create_table "items", force: :cascade do |t|
t.string "product"
t.integer "user_id"
t.integer "item_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.integer "likes_count", default: 0, null: false
end
create_table "likes", force: :cascade do |t|
t.integer "user_id"
t.integer "item_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Given liker is the user who liked post and poster_id is the id of the person who create the post.
liker.likes.joins(:items).where('items.user_id = ?', poster_id).count
Or somethings similar. If you post your annotated model or table schema I can probably come up with a better answer.
After countless reading and experiementing I figured out the answer that worked for me. In case anyone might encounter a similar issue - I have provided the answer that worked for me.
To get total likes by a specific user on all users items - In my controller I put the following
#likersuno = #likers.map(&:likes).flatten.map(&:user).flatten.uniq
And in my index.html.erb
I simply put this and it worked from there
<%= #likersuno.count %>
To get total likes by a specific user on my specific items - In my index.html.erb I put the following and it worked beautifully
<%= liker.likes.select { |like| like.item.user == current_user }.count %>

ActiveRecord AssociationType Mismatch

I have a Rails 3.2.21 app where I'm adding a simple form/collection_select field in my form. When selecting an object from the dropdown (or leaving it blank) I get the following error:
ActiveRecord::AssociationTypeMismatch at /calls/5
BillFacility(#70179530126460) expected, got String(#70179505820040)
Here's what my models look like:
call.rb
belongs_to :bill_facility
attr_accessible :bill_facility_id
bill_facility.rb
has_many :calls
Here's what my form looks like:
_form.html.erb
<%= f.collection_select(:bill_facility_id, BillFacility.order("facility_name ASC"), :id, :facility_name, {:include_blank => true}, {:class => 'select'}) %>
Here's the migrations I did to add the BillFacility model and add the bill_facility_id to the Call model:
class CreateBillFacilities < ActiveRecord::Migration
def change
create_table :bill_facilities do |t|
t.string :facility_name
t.string :facility_address
t.timestamps
end
end
end
class AddBillFaciltyIdToCalls < ActiveRecord::Migration
def change
add_column :calls, :bill_facility_id, :integer
end
end
If I manually assign the call an id in bill_facility_id I get an unknown to_i method error. If I manually make it nil then select a BillFacilty from the drop down (or leave it blank) I get the mismatch error:
ActiveRecord::AssociationTypeMismatch at /calls/5
BillFacility(#70179530126460) expected, got String(#70179505820040)
I'm sure this is something simple that I'm missing. Anyone have any ideas on what I'm doing wrong here? It's a bit early so my mind is kind of fuzzy so I should probably wait until I'm fully awake but figured I'd ask for some help.
If you have any questions, please let me know.
I think I have this figured out. Definitely not awake enough to be writing code.
I had this in my form before the BillFacility collection_select
<%= f.label :Bill_Facility, "Bill Facility", class: "control-label" %><%= f.check_box :bill_facility, :id => 'bill_facility_checkbox' %>
So I was calling a field named bill_facility that was in my database, but since bill_facility is an associated model, it gave me the mismatch error. So I simple altered the migration to change the check_box to bill_fac and it worked.

collection_select throwing error

I have a select box on a form to select the type of category for a project:
<%= f.select(:category, collection_select(:project_category, :cat_id, #project_category, :id, :cat_name)) %>
It should populate from the project_categories table.
The migration looks like this:
class CreateProjectCategories < ActiveRecord::Migration
def change
create_table :project_categories do |t|
t.string :category_name
t.text :cat_desc
t.date :created_on
t.datetime :updated_at
end
end
end
My project.rb model deines has_one :category and the projectCategory.rb model defines belongs_to :project.
My project_categories table is populated with data. I got the syntax from the Rails Guides, but it's not working.
Any help?
Ok, I had the wrong syntax. The final code looks like this:
<%= collection_select(:project_categories, :id, Project_Category.all, :id, :category_name) %>
Essentially the syntax should be defined like this: WARNING: PSEUDO-CODE!!
<%= collection_select(:database_table, :lookup_value, Model_Name.all, :returned_numeric_value, :returned_text_value_based_on_numeric_value) %>
Don't know why the API docs couldn't have just said so...

ActiveRecord::Relation issue on acts-as-taggable-on

I am a rails newbie. I am trying to implement acts-as-taggable-on on my sample app. I am able to enter multiple tags using tag_list but facing issues searching them.
This is what I got.
I used scaffold User to generate the controller & model.
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.text :tags
t.timestamps
end
end
end
My User Model is
class User < ActiveRecord::Base
serialize :tags
acts_as_taggable_on :tags
scope :by_join_date, order("created_at DESC")
end
My User controller
Class UsersController < ApplicationController
def index
#users = User.all
#search = User.tagged_with("Tag11")
end
...
...
...
end
I also did not make any changes to class ActsAsTaggableOnMigration < ActiveRecord::Migration after installing the gem.
In my view I replaced :tags with :tag_list in my _form, index & show html files
<div class="field">
<%= f.label :tags %><br />
<%= f.text_field :tag_list %>
</div>
This is what I get in the browser
Could you please help me understand where I am making a mistake?
Thank you.
I'm guessing (because you haven't provided the code from your other view yet) but:
when you do #search = User.tagged_with("Tag11") what is getting returned is not the tag names, but the actual tag objects. If you have: <%= #search %> in your view, it won't work. You'll need something like:
<%= #search.map(&:name).join(', ') %>
or similar.

Unable to display associated model's fields

Hey all,
I'm having a pretty weird problem and am having trouble isolating the cause. I get the feeling its a simple solution, but I was hoping for a nudge in the right direction. I have the following models:
class User < ActiveRecord::Base
has_many :pnotes
class Pnote < ActiveRecord::Base
belongs_to :preport
belongs_to :user
class Preport < ActiveRecord::Base
has_many :pnotes, :dependent=>:destroy
The Pnote portion of my schema looks as so:
create_table "pnotes", :force => true do |t|
t.integer "preport_id"
t.integer "user_id"
t.text "content"
t.datetime "created_at"
t.datetime "updated_at"
end
I'm trying to display all of the Pnotes associate with a given Preport on the show page of the Preport
My Preport Controller has the following code for the show action:
def show
#board = Board.find(params[:board_id])
#preport = #board.preport
#pnotes = #preport.pnotes
#pnote=#preport.pnotes.build
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #preport }
end
end
So now in my show.html.erb in the Preports folder, I am trying to display a list of the Pnotes as such:
<ul>
<% #pnotes.each do |pnote| %>
<li><%= pnote.user.login %><span>-<%=pnote.content %></span></li>
<% end %>
</ul>
"login" is the standard field that came along with the Devise Authentication Gem.
However, this gives me the following error:
undefined method `login' for nil:NilClass
If I change the view to this:
<%= pnote.user%>-<%=pnote.content %>
I get :
#<User:0x106c25888>-Testing
, so it appears that it is identifying the associated user, but unable to grab its attributes.
Any advice would be greatly appreciated! I feel like there is a fairly small oversight going on here, but I am unable to distinguish from exactly where
Thanks!
Unless you're using a very old version of Devise that I'm not aware of, the User model wouldn't have a login attribute.
Try email instead.