Please help me to display all the comments for certain thread.
I use the following gems:
'awesome_nested_set',
'acts_as_commentable_with_threading'
For example, I create scaffold 'message'. And I try for certain message unit make comments thread.
MessagesController:
def show
# to display all comments
#all_comments = #message.comment_threads
p '-----------------'
p #all_comments
p #all_comments.count
# for form new comment
#message = Message.find(params[:id])
#user_who_commented = current_user
#comment = Comment.build_from( #message, #user_who_commented.id, "Hey guys this is my comment!" )
end
views/messages/show.html.erb:
<p>
<strong>message Title:</strong>
<%= #message.title %>
</p>
<p>
<strong>message Body:</strong>
<%= #message.body %>
</p>
<%= render 'comments/form' %>
<% #all_comments.each do |comment| %>
<div>
<%= #comment.title %>
<%= #comment.body %>
</div>
<% end %>
schema:
create_table "comments", force: :cascade do |t|
t.integer "commentable_id"
t.string "commentable_type"
t.string "title"
t.text "body"
t.string "subject"
t.integer "user_id", null: false
t.integer "parent_id"
t.integer "lft"
t.integer "rgt"
t.datetime "created_at"
t.datetime "updated_at"
end
in this table after add new comment i(and gem) filled via create-action fields:
title,
body,
user_id,
lft,
rgt
CommentsController:
def create
comment = Comment.new(comment_params)
comment.user = current_user
comment.save
if comment.update_attributes(user: current_user)
redirect_to messages_path, notice: 'Comment was successfully created.'
else
render :new
end
end
def new
#comment = Comment.new
end
The form to add a new message worked ok, but all comments for certain messages are not displayed.
ps:
log:
Started GET "/messages/1" for 127.0.0.1 at 2015-10-23 14:09:47 +0300
Processing by MessagesController#show as HTML
Parameters: {"id"=>"1"}
Message Load (0.1ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = ? LIMIT 1 [["id", 1]]
"-----------------"
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = ? AND "comments"."commentable_type" = ? [["commentable_id", 1], ["commentable_type", "Message"]]
#<ActiveRecord::Associations::CollectionProxy []>
(0.1ms) SELECT COUNT(*) FROM "comments" WHERE "comments"."commentable_id" = ? AND "comments"."commentable_type" = ? [["commentable_id", 1], ["commentable_type", "Message"]]
0
CACHE (0.0ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = ? LIMIT 1 [["id", "1"]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
Rendered comments/_form.html.erb (1.0ms)
Rendered messages/show.html.erb within layouts/application (1.9ms)
Completed 200 OK in 40ms (Views: 34.5ms | ActiveRecord: 0.4ms)
Why are you outputting in the show action?
You should only be defining #instance_variables and passing them to the view for rendering:
#config/routes.rb
resources :users do
resources :comments, only: [:show, :create]
end
#app/controllers/messages_controller.rb
class MessagesController < ApplicationController
def show
#message = Message.find params[:id]
end
end
#app/views/messages/show.html.erb
<%= #message.title %>
<%= render #message.comments if #message.comments.any? %>
#app/views/messages/_comment.html.erb
<% comment.title %>
<% comment.body %>
This will output the top-level comments.
If you wanted nested comments, I'd highly recommend using acts_as_tree. This gives you access to "child" objects (set with a parent column in your table), which allows you to do the following:
<%= render #message.comments if #message.comments.any? %>
#app/views/messages/_comment.html.erb
<%= render comment.children if comment.children.any? %>
Notes
1. Vars
When you run a loop (<% #message.comments.each do |comment| %>), you need to use the local variable within the block:
#message.comments.each do |comment|
comment.title
comment.body
end
You're currently using #comment.title -- should be comment.title
-
2. Comment Creation
You can make comment creation through a form embedded in the messages#show view:
#app/views/messages/show.html.erb
<%= render "comments/new" %>
You'd have to make sure you set your #comment variable:
#app/controllers/messages_controller.rb
class MessagesController < ApplicationController
def show
#message = Message.find params[:id]
#comment = Comment.new
end
end
#app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
#comment = Comment.new comment_params
end
private
def comment_params
params.require(:comment).permit(:title, :body)
end
end
You're doing this already, of course - I think it could be cleared up a lot.
-
3. Migration
Finally, you're using a polymorphic association in your table. This should not be used in this case; you should have a standard foreign_key as follows:
create_table "comments", force: :cascade do |t|
t.integer "message_id"
t.string "title"
t.text "body"
t.string "subject"
t.integer "user_id", null: false
t.integer "parent_id"
t.datetime "created_at"
t.datetime "updated_at"
end
This would allow for the following:
#app/models/message.rb
class Message < ActiveRecord::Base
has_many :comments
end
#app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :message
belongs_to :user
acts_as_tree
end
Related
I am trying to create an app that allows users to make lists of items and view only the lists they themselves have created. Every time I press submit on the form this happens
Started POST "/lists" for 127.0.0.1 at 2017-08-18 15:56:40 -0400
Processing by ListsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"VnsMdQq3mw5XabkYCZFTgvgwFc3H89paHA0VE5gunFbiMfa0xGr0p1GEZDHc3yemwBx07K1h4CXuS0l5XL1VbA==", "list"=>{"income"=>"12", "put_into_savings"=>"12", "month"=>"12", "year"=>"21"}, "commit"=>"Create List"}
(0.1ms) begin transaction
(0.1ms) rollback transaction
(0.0ms) begin transaction
(0.0ms) rollback transaction
Rendering lists/new.html.erb within layouts/application
Rendered lists/new.html.erb within layouts/application (9.3ms)
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]]
Completed 200 OK in 269ms (Views: 222.2ms | ActiveRecord: 2.7ms)
Here is all my code:
lists_controller.rb
class ListsController < ApplicationController
def show
#user = User.find(params[:id])
#lists = #user.lists
end
def new
end
def edit
end
def create
#list = List.create(list_params)
if #list.save
redirect_to home_url
else
render :new
end
end
private
def list_params
params.require(:list).permit(:income, :put_into_savings, :month, :year)
end
end
lists/new.html.erb
<%= form_for List.new do |f| %>
<div class="field">
<%= f.label :income %><br />
<%= f.text_field :income %>
</div>
<div class="field">
<%= f.label :put_into_savings %><br />
<%= f.text_area :put_into_savings %>
</div>
<div class="field">
<%= f.label :month %><br />
<%= f.number_field :month %>
</div>
<div class="field">
<%= f.label :year %><br />
<%= f.number_field :year %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
schema.rb
ActiveRecord::Schema.define(version: 20170818185700) do
create_table "items", force: :cascade do |t|
t.string "item_name"
t.integer "item_cost"
t.string "item_waste"
t.string "item_group"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "lists", force: :cascade do |t|
t.integer "income"
t.integer "put_into_savings"
t.string "month"
t.string "year"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "Item_id"
t.integer "User_id"
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "name"
end
end
Routes.rb
Rails.application.routes.draw do
root 'home#index'
get 'home' => 'home#index'
resources :lists
resources :sessions, only: [:new, :create, :destroy]
resources :users, only: [:new, :create]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
Here is my list model:
class List < ApplicationRecord
has_many :items
belongs_to :user
end
How can I solve this?
You are having logic problem with your model association.
Assuming that a List could have more than one Item, you shouldn't have declared your table List with the attribute item_id. (Doing that it means a List could ONLY have one item). I recommend you read ruby-on-rais-guide-for-associations.
For the problem with the user_id, you need to explicit declared the user_id in your list object (considering that you want to associate a List with a User in the moment the List is created). One way to do it could be:
def create
#list = List.new(list_params)
#list[:user_id] = current_user.id # Considering you add this method
if #list.save
redirect_to home_url
else
render :new
end
And add some validation in model:
class List < ApplicationRecord
has_many :items
belongs_to :user
validates :user_id, presence: true
end
It seems you need to read more about validation too ruby-on-rais-guide-for-validation. About your twice rollback, it is unclear the reason, but fixing you association and validations problems, I think you can fix it.
Try read more about rails, the problem you are having are really basic. Good luck!
UPDATE:
As suggested by at0misk answer, to solve the problem with twice rollback:
In List controller:
#list = List.new(list_params)
# instead of #list = List.create(list_params)
The create method create a new object and save immediately. So, rails was trying to save twice, in the method create first, then in the method save in sequence.
In your create method, you're calling create and then calling save. Create creates an object and saves it to the database, so calling save is redundent.
Have you checked to see if your record is saving? If it is then this is definitely what's wrong. I prefer to use this pattern, using new instead of create, and then attempting to save in an if block:
def create
#list = List.new(list_params)
if #list.save
redirect_to home_url
else
render :new
end
end
Be easy on me, I'm just starting to learn Rails and this is my first question on here!
The project I'm using to learn is a volleyball scoreboard, so right now I'm trying to build a form that will submit the score of a 2v2 game. I have users and games which are associated by a has_many through relationship to a join table of participants which also includes a 'result' attribute ('W' or 'L').
My problem is that when I submit it fails, and no participants are created. If I removed the associations from the form, submission will work with just game parameters.
Hopefully, I've included all the relevant information below. Also, if there is a better way to do all this, I'd love to hear it!
MODELS
class Game < ApplicationRecord
has_one :venue
has_many :participants
has_many :users, through: :participants
accepts_nested_attributes_for :participants,
reject_if: :all_blank, allow_destroy: true
end
class User < ApplicationRecord
has_many :participants
has_many :games, through: :participants
end
class Participant < ApplicationRecord
belongs_to :game
belongs_to :user
end
SCHEMA
create_table "games", force: :cascade do |t|
t.date "game_date"
t.integer "winning_score"
t.integer "losing_score"
t.text "notes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "venue_id"
t.index ["venue_id"], name: "index_games_on_venue_id"
end
create_table "participants", force: :cascade do |t|
t.integer "user_id"
t.integer "game_id"
t.string "result"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["game_id"], name: "index_participants_on_game_id"
t.index ["user_id"], name: "index_participants_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.index ["email"], name: "index_users_on_email", unique: true
end
create_table "venues", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
CONTROLLER
class GamesController < ApplicationController
def show
#game = Game.find(params[:id])
end
def new
#users = User.all
#game = Game.new
#game.participants.build
end
def create
#game = Game.new(game_params)
if #game.save
redirect_to 'show'
else
render 'new'
end
end
private
def game_params
params.require(:game).permit(:game_date, :winning_score,
:losing_score, :notes, :venue_id,
participants_attributes: [:user_id, :result,
:_destroy])
end
end
FORM
<%= simple_form_for #game do |f| %>
<div id="winners">
<b>Winners</b>
<% for i in 0..1 %>
<%= f.simple_fields_for :participants do |p| %>
<%= p.association :user, :collection => #users, label: false %>
<%= p.input :result, :as => :hidden, :input_html => { :value => 'W' }%>
<% end %>
<% end %>
</div>
<%= f.input :winning_score, :collection => 15..30 %>
<div id="losers">
<b>Losers</b>
<% for i in 2..3 %>
<%= f.simple_fields_for :participants do |p| %>
<%= p.association :user, :collection => #users, label: false %>
<%= p.input :result, :as => :hidden, :input_html => { :value => 'L' }%>
<% end %>
<% end %>
</div>
<%= f.input :losing_score, :collection => 0..30 %>
<%= f.input :notes %>
<%= f.submit "Submit!", class: "btn btn-primary" %>
<% end %>
RESPONSE
Processing by GamesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8081+wU7EqYV7PIIAOGP3N+Md4CJusFpL9qTm3CeC54fP7pTPEwtfYS5v5x+ErBWxGiB0oj1pklYGXwl/cRBw==", "game"=>{"participants_attributes"=>{"0"=>{"user_id"=>"3", "result"=>"W"}, "1"=>{"user_id"=>"2", "result"=>"W"}, "2"=>{"user_id"=>"1", "result"=>"W"}, "3"=>{"user_id"=>"6", "result"=>"W"}}, "winning_score"=>"18", "losing_score"=>"4", "notes"=>"13241234"}, "commit"=>"Submit!"}
(0.1ms) begin transaction
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 6], ["LIMIT", 1]]
(0.1ms) rollback transaction
Rendering games/new.html.erb within layouts/application
Rendered games/new.html.erb within layouts/application (69.4ms)
Rendered layouts/_shim.html.erb (0.4ms)
Rendered layouts/_header.html.erb (0.7ms)
Rendered layouts/_footer.html.erb (0.3ms)
Completed 200 OK in 199ms (Views: 144.9ms | ActiveRecord: 0.5ms)
#kkulikovskis comment worked for me. I changed:
has_many :participants
to
has_many :participants, inverse_of: :game
in the game model
please help solve the problem.
models:
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :tags
end
tables:
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "body"
t.integer "user_id"
end
create_table "posts_tags", id: false, force: :cascade do |t|
t.integer "post_id"
t.integer "tag_id"
end
create_table "tags", force: :cascade do |t|
t.string "tagname"
end
form:
<%= form_for [#user, #post] do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :body %>
<%= f.text_area :body %>
<label class="lbl_tagname"><%=t :tags %></label>
<%= text_field_tag 'tagnames', nil, class: 'tagnames' %>
<%= f.submit %>
<% end %>
post controller:
def new
#user = User.find(params[:user_id])
#post = Post.new
end
def create
#post = current_user.posts.build(post_params)
if #post.save
add_new_tags(#post)
flash[:success] = t :post_saved
redirect_to user_post_path(#current_user, #post)
else
flash.now[:error] = t :post_not_saved
render 'new'
end
end
private
def add_new_tags(post)
tagnames = params[:tagnames].split(/[, \.?!]+/)
tagnames.each do |tagname|
tagname_exist = Tag.find_by tagname: tagname.downcase
tag = Tag.create(tagname: tagname.downcase) if !tagname_exist
tag.posts.push post
p '=============='
p post.id
p '=============='
end
end
def post_params
params.require(:post).permit(:title, :body, :tagnames)
end
a user visits a page, see the form. fill in the form below. sends. resulting record is not added to the table posts_tags.
displays the following error message:
NoMethodError in PostsController#create
undefined method `posts' for nil:NilClass
the console displays the following:
"=============="
391
"=============="
Tag Load (0.1ms) SELECT "tags".* FROM "tags" WHERE "tags"."tagname" = ? LIMIT 1 [["tagname", "asd"]]
Completed 500 Internal Server Error in 904ms (ActiveRecord: 811.8ms)
NoMethodError (undefined method `posts' for nil:NilClass):
app/controllers/posts_controller.rb:93:in `block in add_new_tags'
app/controllers/posts_controller.rb:89:in `each'
app/controllers/posts_controller.rb:89:in `add_new_tags'
app/controllers/posts_controller.rb:45:in `create'
wherein. in table post entry is created
def add_new_tags(post)
tagnames = params[:tagnames].split(/[, \.?!]+/)
tagnames.each do |tagname|
tag = Tag.find_or_create_by(tagname: tagname.downcase)
tag.posts << post
end
end
You need to push post to tag only after initilizing tag variable
tag = tagname_exist || Tag.create(tagname: tagname.downcase)
tag.posts.push post
I created a cookbook scaffold, allowing users to create many cookbooks. I associated the user_id to the cookbook in the controller, but the title and description is showing up nil in the rails database.
class CookBooksController < ApplicationController
before_action :set_cook_book, only: [:show, :edit, :update, :destroy]
# GET /cook_books
# GET /cook_books.json
def index
#cook_books = CookBook.all
end
# GET /cook_books/1
# GET /cook_books/1.json
def show
end
# GET /cook_books/new
def new
#cook_book = CookBook.new()
end
# GET /cook_books/1/edit
def edit
end
# POST /cook_books
# POST /cook_books.json
def create
#cook_book = CookBook.new(cook_book_params)
#cook_book.user_id = current_user.id
respond_to do |format|
if #cook_book.save
format.html { redirect_to #cook_book, notice: 'Cook book was successfully created.' }
format.json { render :show, status: :created, location: #cook_book }
else
format.html { render :new }
format.json { render json: #cook_book.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cook_books/1
# PATCH/PUT /cook_books/1.json
def update
respond_to do |format|
if #cook_book.update(cook_book_params)
format.html { redirect_to #cook_book, notice: 'Cook book was successfully updated.' }
format.json { render :show, status: :ok, location: #cook_book }
else
format.html { render :edit }
format.json { render json: #cook_book.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cook_books/1
# DELETE /cook_books/1.json
def destroy
#cook_book.destroy
respond_to do |format|
format.html { redirect_to cook_books_url, notice: 'Cook book was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cook_book
#cook_book = CookBook.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cook_book_params
params.require(:cook_book).permit(:title, :user_id, :description)
end
end
class CookBook < ActiveRecord::Base
belongs_to :users
end
ActiveRecord::Schema.define(version: 20140811235307) do
create_table "cook_books", force: true do |t|
t.string "title"
t.integer "user_id"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pages", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.text "header"
end
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "username"
t.string "country"
t.string "address"
t.string "provider"
t.string "uid"
t.boolean "admin", default: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
Any help appreciate it! thank you
EDIT! Form added
<%= form_for(#cook_book) do |f| %>
<% if #cook_book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#cook_book.errors.count, "error") %> prohibited this cook_book from being saved:</h2>
<ul>
<% #cook_book.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
EDIT! Server Log
Started GET "/cook_books/new" for 127.0.0.1 at 2014-08-12 02:21:05 -0400
ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by CookBooksController#new as HTML
Rendered cook_books/_form.html.erb (30.2ms)
Rendered cook_books/new.html.erb within layouts/application (36.9ms)
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered layouts/_header.html.erb (28.2ms)
Completed 200 OK in 335ms (Views: 306.3ms | ActiveRecord: 1.7ms)
Started POST "/cook_books" for 127.0.0.1 at 2014-08-12 02:21:15 -0400
Processing by CookBooksController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"TNDketl0ixC8Lh/aAWIGf7SWeiwHZR9ITlEEpa7/+xM=", "cook_book"=>{"title"=>"Test title", "description"=>"test description "}, "commit"=>"Create Cookbook"}
**WARNING: Can't mass-assign protected attributes for CookBook: title, description
app/controllers/cook_books_controller.rb:28:in `create'** (Just saw this)
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (0.9ms) INSERT INTO "cook_books" ("created_at", "updated_at", "user_id") VALUES (?, ?, ?) [["created_at", "2014-08-12 06:21:15.547634"], ["updated_at", "2014-08-12 06:21:15.547634"], ["user_id", 1]]
(1.4ms) commit transaction
Redirected to http://localhost:3000/cook_books/8
Completed 302 Found in 29ms (ActiveRecord: 2.9ms)
Started GET "/cook_books/8" for 127.0.0.1 at 2014-08-12 02:21:15 -0400
Processing by CookBooksController#show as HTML
Parameters: {"id"=>"8"}
CookBook Load (0.4ms) SELECT "cook_books".* FROM "cook_books" WHERE "cook_books"."id" = ? LIMIT 1 [["id", 8]]
Rendered cook_books/show.html.erb within layouts/application (1.4ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered layouts/_header.html.erb (2.3ms)
Completed 200 OK in 34ms (Views: 30.9ms | ActiveRecord: 0.7ms
)
EDIT! Model
class CookBook < ActiveRecord::Base
belongs_to :users
end
Your Code is fine,but when looked at the server log,you have this warning
Can't mass-assign protected attributes for CookBook: title,
description
And from the comments,it is confirmed that you have this gem protected_attributes.This adds the default attr_accessible.But when it comes with Rails4,this gem is not required.You need to remove it to get the things work.
A small note:
As #Jaugar Chang pointed,you have belongs_to :users.It should be belongs_to :user.It would lead to further problems.
Currently I have an edit form as follows:
<li>
<%= form_for #ingredient do |f| %>
<span class="span2"><%= f.text_field :name, placeholder: "#{#ingredient.name}" %></span>
<span class="span1"><%= f.text_field :quantity, placeholder: "#{#ingredient.quantity}" %></span>
<span class="span1"><%= f.text_field :unit, placeholder: "#{#ingredient.unit}" %></span>
<span class="span3">Added: <%= #ingredient.updated_at.strftime("%d %b. at %H:%M") %></span>
<span class="span2"><%= f.text_field :expiration, placeholder: "#{#ingredient.expiration}" %></span>
<span class="span2"><%= f.submit "Submit", class: "btn btn-small" %></span>
<% end %>
</li>
When I click submit my log file shows the follow:
Started PATCH "/pantries/112" for 127.0.0.1 at 2014-04-29 18:03:35 -0400
Processing by PantriesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NUSmadjWCVVLHOZmncKD5D48L+7ZMa3DEbZ9Y+Y+Pnc=", "pantry"=>{"name"=>"test1", "quantity"=>"1", "unit"=>"cup", "expiration"=>"2015-05-05"}, "commit"=>"Submit", "id"=>"112"}
[1m[35mUser Load (0.5ms)[0m SELECT "users".* FROM "users" WHERE "users"."remember_token" = '27ecdc04fc67375fd3567c89fbe831e4d4919d09' LIMIT 1
[1m[36mPantry Load (0.3ms)[0m [1mSELECT "pantries".* FROM "pantries" WHERE "pantries"."id" = $1 LIMIT 1[0m [["id", "112"]]
[1m[35m (0.2ms)[0m BEGIN
[1m[36m (0.1ms)[0m [1mCOMMIT[0m
Redirected to http://localhost:3000/users/1/pantry
Completed 302 Found in 6ms (ActiveRecord: 1.1ms)
It doesn't raise an error it just does not update at all, but says that the update completed successfully.
pantry.rb
class Pantry < ActiveRecord::Base
before_save { self.name = name.downcase }
belongs_to :user
validates :name, presence: true
validates :user_id, presence: true
end
pantries_controller
def update
#ingredient = Pantry.find(params[:id])
if #ingredient.update_attributes(params[ingredient_params])
redirect_to pantry_user_path(current_user), :flash => {info: "Ingredient Updated"}
else
redirect_to pantry_user_path(current_user), :flash => {info: "Failed"}
end
end
private
def ingredient_params
params.require(:pantry).permit(:name, :quantity, :unit, :expiration, :created_at, :updated_at)
end
schema:
create_table "pantries", force: true do |t|
t.string "name"
t.string "quantity"
t.string "unit"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
t.date "expiration"
end
add_index "pantries", ["expiration"], name: "index_pantries_on_expiration", using: :btree
add_index "pantries", ["quantity"], name: "index_pantries_on_quantity", using: :btree
add_index "pantries", ["unit"], name: "index_pantries_on_unit", using: :btree
If I replace #ingredients.update_attributes with #ingredient.update_column(:expiration, params[:pantry][:expiration]) the update takes place on that column. Falling back to update_column is not ideal. I understand update_attributes and update_attributes! call callbacks while update_column does not. I don't see any issue with the callbacks and no error messages are given. Anyone have an idea on what the issue might be?
Change your update action as below:
def update
#ingredient = Pantry.find(params[:id])
if #ingredient.update_attributes(ingredient_params) ## Call ingredient_params
redirect_to pantry_user_path(current_user), :flash => {info: "Ingredient Updated"}
else
redirect_to pantry_user_path(current_user), :flash => {info: "Failed"}
end
end
With Rails 4 strong parameters concept, you need to whitelist the attributes that you would like to be saved in database.
Currently, you are using params[ingredient_params] instead of calling ingredient_params which is causing this issue