Rails 3 array - add items with category then list items in category - arrays

As part of my Rails 3 app, I want the User to be able to click on links on other profiles/pages and have the string value of the link be added to an array belonging to that User's profile.
Specifically, what I am looking to do is populate a list of :todos for each profile depending on which todo they click. The idea is that each todo will fall within one of two categories: inside and outside. So clicking the links will push the value of the todo to either inside or outside. Then the User's profile will display a list of :todos inside and outside, and count the total of todos for that User's profile.
Since I'm a beginner to programming, I got some help here on SO about setting this up; however I need some help finishing it. I can't quite seem to connect all the dots. I've set up a join model but am not able to add the todo's string value, then list/count it in the profile. Here is my code:
profile.rb Model:
class Profile < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
has_many :profile_todos
has_many :todos, :through => :profile_todos
def add_todo_inside_item(item)
self.profile_todos.build :category => 'inside'
end
def add_todo_outside_item(item)
self.profile_todos.build :category => 'outside'
end
end
todo.rb Model:
class Todo < ActiveRecord::Base
belongs_to :profile
end
profile_todo.rb Model:
class ProfileTodo < ActiveRecord::Base
belongs_to :profile
belongs_to :todo
end
_create_todos.rb Migration:
class CreateTodos < ActiveRecord::Migration
def self.up
create_table :todos do |t|
t.string :name
t.timestamps
end
end
_create_profile_todos.rb Migration:
class CreateProfileTodos < ActiveRecord::Migration
def self.up
create_table :profile_todos do |t|
t.string :category
t.integer :profile_id
t.timestamps
end
end
Listing the todos in a User's Profile:
<div id="todos">
<p><%= #profile.first_name %> has <%= pluralize(#profile.profile_todos.count, 'goal') %>.</p>
<div id="todo-list">
<div class="todos_inside">
<p><%= #profile.profile_todos(:category => 'inside' %>.</p>
</div>
<div class="todos_outside">
<p><%= #profile.profile_todos(:category => 'outside' %>.</p>
</div>
</div>
</div>
add_item to #profile.todos:
<li><%= link_to "#", :class => 'button white' do %><%= #user.profile.stringtoadd %><% end %></li>

As #socjopata mentioned, you're going to need some sort of controller action to manage the creation and building of your ProfileTodo records. Since you already created a ProfileTodo join model, go ahead and create a ProfileTodosController.
More on controllers:
http://guides.rubyonrails.org/action_controller_overview.html
Your link_to tag should then make a remote call to the create action. In order to get everything to work properly, you'd most likely need to supply the controller with both the profile_id and topic_id in order to make the correct RESTful transaction, which means you'll have to supply a parameter hash to your link_to tag, which can get kinda messy if you use the url_options.
Look at passing in url_options:
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
Ultimately, you are creating a new ProfileTodo record, so I think it would be a better description of the work being done if you used a form_for tag that has hidden fields for the profile_id and the topic_id. You can also make forms remote in rails by supplying them with :remote => true
Assuming you make an accompanying controller and add RESTful resources to your config/routes.rb file, your form for each individual topic would look something like this:
<%= form_for(profile_todo_path, :remote=> true) do |f| %>
<%= f.hidden_field_tag :profile_id, :value => #user.profile.id %>
<%= f.hidden_field_tag :topic_id, :value => topic.id %>
<%= f.submit_tag topic.name %>
<% end %>
You can always style your forms, so if you only want a link to be displayed, that should be doable :)

You rather need a remote link pointing to some action, so you can manipulate your todos without refreshing the page. From the docs:
:remote => true - This will allow the unobtrusive JavaScript driver to
make an Ajax request to the URL in question instead of following the
link. The drivers each provide mechanisms for listening for the
completion of the Ajax request and performing JavaScript operations
once they’re complete
As for the other question, you can define scopes you'll use for displaying and counting objects:
http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html

Related

Remove an element from the result of an Active Record query

I am new to Rails and I am having a problem with the results of an Active Record query.
I have a Class method (this_week ) that returns 3 recipe records from my database. I would like to delete one of the returned records from the query (not the database) while maintaining the other 2 records.
When I am in my View for the Index page, and try to delete one of the records that is returned I get the following error: “Routing Error No route matches [GET] "/Lomo%20saltado”
How can I delete this part of the returned query?
Any help that could be provided would be greatly appreciated.
Model
class LineItem < ActiveRecord::Base
belongs_to :recipe
belongs_to :recipe_collection
def self.this_week
#line_items = LineItem.order("RANDOM()").limit(3)
#line_items.map{ |line_item| line_item.recipe.title }
end
end
View
<%= #line_items.this_week[0] %> <%=link_to 'Remove', #line_items.this_week.delete_at(0) %> <br>
Controller
class LineItemsController < ApplicationController
include UserRecipe #Error: Couldn't find recipe with id / off: undefined meth: Set_rec_collect
before_action :set_recipe_collection, only: [:create]
before_action :set_line_item, only: [:show, :edit, :update, :destroy, :last_eaten]
def index
#line_items = LineItem.where(nil)
#line_items = LineItem.all
#line_items.this_week
end
Routes
Rails.application.routes.draw do
resources :line_items
resources :recipe_collections
devise_for :users
resources :recipes
root "recipes#index"
end
Here is one of the solutions:
in your view:
<%=link_to 'Remove', #line_items(remove_item: params[:remove_item].to_i + 1) %>
in your controller:
#line_items = LineItem.all
#line_items = #line_items.limit(LineItem.count - params[:remove_item].to_i) if params[:remove_item].present?

Rails 4.1.4 ActionController param is missing or the value is empty: name

I am relatively new to learning how to code and I am really having problems understanding how to write the code for dealing with parameters in a private method in the controller of a Rails 4.1.4 app so that my app works correctly by allowing me to enter a new picture album name, save it to the db, and have it be persisted so that the name of the new album added shows correctly (currently, it does not work right at all). Can someone please help me? Any help at all would be greatly appreciated.
Here is my code for my albums controller:
class AlbumsController < ApplicationController
def index
#albums = Album.all
end
def new
#album = Album.new
end
def create
#album = Album.new(album_params)
#album.save
redirect_to albums_path
end
def show
#album = Album.find(params[:id])
end
def edit
end
def update
end
private
def album_params
params.require(:name).permit(:id, :category)
end
end
Also, here is my album model:
class Album < ActiveRecord::Base
belongs_to :user
has_many :photos
end
And here is my migration for the albums:
class CreateAlbums < ActiveRecord::Migration
def change
create_table :albums do |t|
t.string :name # Column for album name of type string
t.string :category # Column for photography category of type string
t.timestamps
end
end
end
Here is my code for my app/views/albums/index.html.erb file:
<div><%= link_to "Admin Access to Add New Album", new_album_path %></div>
<div><%= link_to "Home", root_path %></div>
<h1>Albums Gallery</h1>
<% #albums.each do |album| %>
<div><%= link_to album.name, "/albums/#{album.id}" %></div>
<% end %>
Here is my code from my app/views/albums/new.html.erb file where I use the form_for thing:
<h2>New Albums</h2>
<%= link_to "Back", albums_path %>
<%= form_for (#album) do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<%= f.submit "Add Album" %>
<% end %>
Everything up to the form_for part where I try to enter a new picture album name works. It's at this point where everything just unravels and won't work for me. Instead of accepting and then showing the new album by name, it displays "/albums/3" when it should display "Nature Scenes". I went into my rails console to see what was going on on the db level and the new albums are not being created and saved correctly. My output from the Rails console looks like this:
2.1.2 :007 > Album.all Album Load (0.2ms) SELECT "albums".* FROM "albums" => #, #, #,
, #
nil, category: nil, created_at: "2014-09-21 02:50:54", updated_at:
"2014-09-21 02:50:54">]>
2.1.2 :008 >
(Sorry about the copy/paste, but being too new at trying to learn how to code, I don't have enough reputation points on Stackoverflow to be allowed to simply post a screenshot yet.)
OK, never mind, I got it. I had the wrong value in the private method. I changed it to
def album_params
params.require(:album).permit(:id,:name, :category)
end
And now the app works fine (at least, so far - I have a long way to go to complete it).

How to update a nested collection_check_box

I have a form for a child (categorization) nested within the parent form (project). The categorization attributes are created using a collection_check_boxes helper like so:
<%= f.fields_for :categorizations do |cat| %>
<%= collection_check_boxes :categorization, :category_id, #categories, :id, :display_name %>
<% end %>
In the Projects controller I'm able to successfully create the new records:
def create
#project = Project.new(project_params)
valid_categorizations = params[:categorization][:category_id].reject! { |c| c.empty?}
#project.categorizations.build(valid_categorizations.map{|cat| {category_id: cat}})
...
end
...
def project_params
params.require(:project).permit(:slug, :title, :body, :published, :category_ids => [])
end
Now, when I want to edit the parent Project record the collection_check_boxes does two undesirable things:
It does not pre-populate attributes (like the .include?(attribute) in a traditional check box), and
It repeats the set of check boxes N times depending on how many categorization records exist in the database (e.g., if Project #1 has three Categorization records the entire set of check boxes will display three times in the edit form).
I can't figure out how to fix this, so any help is greatly appreciated!

Rails 4 : basic use of Merit gem with Devise

Using the merit gem, I want to create a Pioneer badge for the first 100 users of my app.
The code in merit.rb
Merit::Badge.create!(
id: 1,
name: 'Pioneer',
description: "Belongs to the 100 first users of the site",
image: '/images/pioneer.png'
)
The code from badges_rules.rb takes in consideration that i'm using devise for authentification. So I followed this how to.
grant_on 'users/registrations#create', badge: 'Pioneer', model_name: 'User' do |user|
user.id < 101
end
It's not creating any badge. It's interesting to notice that this other badge is working very well :
grant_on 'users/registrations#create', badge: 'Inscription', model_name: 'User'
It seems that Devise is messing with the user object. I did override the registration controller, exactly like the Howto said. And when I call this controller in a simple way, like with this "Inscription" badge, everything's ok.
But when I need to put a condition on the user's id, nothing happens.
For information, this is the code from user's show view, where the badges are displayed (this is working).
<% #user.badges.first(5).each do |b| %>
<%= image_tag(b.image) %>
<%= b.name %>
<%end%>
Add model_name: 'User' to your rule. This happens when the controller name is not named after the object (registrations != user).

how pass variables by arrays not db records?

I'm currently building a data generator. First I want to implement is PESEL (kind of personal ID in Poland based on birth date) generator - I want to enter in form a temporary data with start and end birth date interval - I don't want to store it in database (or I should I do it?)
Here is my pesel controller:
def new
#pesel = Array.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #pesel }
end
end
but I've got an "undefined method `model_name' for NilClass:Class" error - is it a good way anyway of solvint this case? I read somewhere that using temporary variables is not with 'The Ruby Way' - if my solution is wrong, please suggest the correct one. (e.g pass this vars through cookies? hash? helper method?)
here is the stacktrace(I think):
Started GET "/pesel" for 127.0.0.1 at 2011-12-05 16:18:20 +0100
Processing by PeselController#new as HTML
Rendered pesel/new.html.erb within layouts/application (1513.9ms)
Completed 500 Internal Server Error in 1793ms
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
1: <%= simple_form_for #pesel do |f| %>
2: <%= f.input :date_of_birth, :as => :date, :start_year => Date.today.year - 90,
3: :end_year => Date.today.year - 12, :discard_day => true,
4: :order => [:month, :year] %>
app/views/pesel/new.html.erb:1:in `_app_views_pesel_new_html_erb__708648673_90148530'
app/controllers/pesel_controller.rb:7:in `new'
Rendered /home/ofca/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (5.6ms)
Rendered /home/ofca/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (4.0ms)
Rendered /home/ofca/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.1/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (17.6ms)
form_for assumes certain properties exist for the object you pass it, such as model_name.
Instead of using form_for #pesel, just use form_tag and the related _tag methods.
Use a Pesel model. Models are not tables, and your model doesn't have to write anything to the database. Just don't inherit from ActiveRecord, but do provide a model_name and any other fields the form_for helper expects.

Resources