Ajax form not rendering partial - javascript

I'm trying to implement a follow/unfollow form to create/destroy a relationship between a user, and a company on a site. I'm having problems rendering a new partial on form submit, to change the relationship button from "follow" to "unfollow"
Currently, I render a different partial depending on whether or not a relationship already exists:
`<% unless current_user.id == #company.user_id %>
<div id="#relationship">
<% if current_user.following?(#company) %>
<%= render :partial => 'unfollow' %>
<% else %>
<%= render :partial => 'follow' %>
<% end %>
</div>
<% end %>`
The follow partial looks like:
<%= form_for(current_user.relationships.build(followed_id: #company.id), remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow",class: "btn-transparent btn-hollow btn-huge" %>
<% end %>
While the unfollow partial looks like:
<%= form_for(current_user.relationships.find_by(followed_id: #company.id), html: { method: :delete }, remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn-transparent btn-hollow btn-huge" %>
<% end %>
These use Create and Destroy methods in my Relationships_Controller:
class RelationshipsController < ApplicationController
before_filter :authenticate_user!
def create
#company = Company.find(params[:relationship][:followed_id])
current_user.follow!(#company)
respond_to do |format|
format.html { redirect_to #company }
format.js {render layout: false}
end
end
def destroy
#company = Relationship.find(params[:id]).followed
current_user.unfollow!(#company)
respond_to do |format|
format.html { redirect_to #company }
format.js{render layout: false}
end
end
end
If I set remote: false, the form works as expected, creating and destroying relationships, and the button changes on page reload. When I try to use AJAX by setting remote: true, and use the code below for relationships/create.js.erb and relationships/destroy.js.erb
$("#relationship").html("<%= j render('companies/unfollow') %>");
$("#relationship").html("<%= j render('companies/follow') %>");
However, now when I reload my page - I can click on the button once to create/destroy a relationship object. If I click again, I get a 500 error. The new partial is never loaded.
Although I'm a bit of a noob, this error in seems to point me to this line in the jquery source in chrome dev tools:
xhr.send( ( options.hasContent && options.data ) || null );
I'm using Rails 4, Jquery-Turbolinks and Devise - if any of them bare any relevance to the problem.
Incredibly frustrated now, if anyone could help that would be greatly appreciated!
Update
The log output is below. The first DELETE says that it has rendered my partial, however it has not. The second DELETE is what is happening on clicking unfollow a second time - it rightly points out that the Relationship with that id number no longer exists, as it was deleted on the first action.
Started DELETE "/relationships/429" for 127.0.0.1 at 2014-10-28 14:34:59 +0000
Processing by RelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "commit"=>"Unfollow", "id"=>"429"}
[1m[36mUser Load (1.0ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1[0m
[1m[35mRelationship Load (0.4ms)[0m SELECT "relationships".* FROM "relationships" WHERE "relationships"."id" = $1 LIMIT 1 [["id", 429]]
[1m[36mCompany Load (0.3ms)[0m [1mSELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT 1[0m [["id", 1]]
[1m[35mRelationship Load (0.3ms)[0m SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = $1 AND "relationships"."followed_id" = 1 LIMIT 1 [["follower_id", 1]]
[1m[36m (0.2ms)[0m [1mBEGIN[0m
[1m[35mSQL (3.6ms)[0m DELETE FROM "relationships" WHERE "relationships"."id" = $1 [["id", 429]]
[1m[36m (0.5ms)[0m [1mCOMMIT[0m
Rendered companies/_follow.html.erb (2.5ms)
Rendered relationships/destroy.js.erb (5.3ms)
Completed 200 OK in 19ms (Views: 7.0ms | ActiveRecord: 6.3ms)
Started DELETE "/relationships/429" for 127.0.0.1 at 2014-10-28 14:35:04 +0000
Processing by RelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "commit"=>"Unfollow", "id"=>"429"}
[1m[35mUser Load (0.9ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
[1m[36mRelationship Load (0.3ms)[0m [1mSELECT "relationships".* FROM "relationships" WHERE "relationships"."id" = $1 LIMIT 1[0m [["id", 429]]
Completed 404 Not Found in 4ms
ActiveRecord::RecordNotFound - Couldn't find Relationship with 'id'=429:

You have a hash in the name of your ID.
Try changing
<div id="#relationship">
to
<div id="relationship">

When use remote: true you must change:
format.js{render layout: false}
with
format.js
Otherwise: you never render relationships/create.js.erb and relationships/destroy.js.erb

Related

Passing nested parameters for instance variables

strong textI'm trying to make dynamic select boxes via "data-remote attribute for select boxes". In console it seems that i'm getting right parameters(the id of selected make), but I can't figure it out how to pass it to controller to get models with matching make_id:s.
Heres the attached_vehicles form part from _form.html.erb
<div class="vehicle_field">
<%= f.fields_for :attached_vehicles do |av| %>
<p>Select make</p>
<%= av.select :make, (#makes.collect { |m| [m.make_name, m.id] }), { include_blank: "Select make" }, { data: { remote: true, url: "update_make_models", name: "make", update: "#diy_attached_vehicles_attributes_0_model"} } %><br>
<p>Select model</p>
<%= av.collection_select :model, #models, (render "make_models/make_model"), { prompt: "Select model" } %><br>
...
<% end %>
</div>
../views/diys/update_make_models.coffee
$.empty()
.append("<%= escape_javascript(render "make_models/make_model") %>")
../diys_controller.rb
...
def update_make_models
#models = MakeModel.where("make_id = ?", params[:make])
end
def new
#diy = Diy.new
#step = #diy.steps.new
#attached_vehicle = #diy.attached_vehicles.new
#step.add_images_to_steps.new
#makes = Make.all
#models = MakeModel.where("make_id = ?", params[:make_id])
end
...
../views/make_models/_make_model.html.erb
<% #models.collect do |models| %>
<option value="<%= models.id %>"><%= models.make_model_name %></option>
<% end %>
And here's what i'm getting in console after selecting make in makes select box
Started GET "/diys/update_make_models?diy%5Battached_vehicles_attributes%5D%5B0%5D%5Bmake%5D=12" for ::1 at 2016-02-18 20:22:35 +0200 Processing by DiysController#update_make_models as JS
Parameters: {"diy"=>{"attached_vehicles_attributes"=>{"0"=>{"make"=>"12"}}}}
MakeModel Load (1.0ms) SELECT "make_models".* FROM "make_models" WHERE (make_id = NULL)
Rendered make_models/_make_model.html.erb (3.0ms)
Rendered diys/update_make_models.coffee (491.0ms)
Completed 200 OK in 628ms (Views: 626.5ms | ActiveRecord: 1.0ms | Solr: 0.0ms)
------------------------------------------------------------------------------------------------------------------------------------
Edit
NameError (undefined local variable or method `attached_vehicles_attributes' for #<DiysController:0x5757648>):
app/controllers/diys_controller.rb:28:in `update_make_models'
Your params hash is(according to logs): {"diy"=>{"attached_vehicles_attributes"=>{"0"=>{"make"=>"12"}}}}. So, if you want to get :make_id from it, you should write:
def update_make_models
#models = MakeModel.where(make_id: params["diy"]["attached_vehicles_attributes"]["0"]["make"])
end

Rails Acts_as_votable ajax/js upvoting all posts instead of one

Okay, I'm starting to pull my hair out on this one. I'm new to rails, and was following a tutorial on making a pinterest style app. I finished it but wasn't happy with the up-voting system.
It was refreshing the page every time I clicked to up vote. So I found some post about it and did exactly what it said. It kept loading a page that showed me the js code instead of executing it.
This morning I changed a "put" to "get" then back again, and now it's working... NO IDEA what happened to change it.
BUT, now it's up voting every post on the page instead of just the one I click on. When I hover over the links, they all point to the proper ID for that link.
Here's the code from the controller:
def upvote
#pin.upvote_by current_user
respond_to do |format|
format.html { redirect_to :back }
format.js { render :layout => false }
format.json
end
end
And the view (haml):
.btn-group.pull-right
= link_to like_pin_path(pin), method: :put, remote: true, class: "btn btn-like" do
%span.glyphicon.glyphicon-heart
= pin.get_upvotes.size
Upvote.js.erb:
$('.glyphicon-heart').html('<%=#pin.get_upvotes.size%>');
Routes.rb
Rails.application.routes.draw do
devise_for :users
resources :pins do
member do
put "like", to: "pins#upvote", defaults: { format: 'js' }
end
end
root "pins#index"
end
Here's the log from the console when a like button is clicked:
Started PUT "/pins/10/like" for ::1 at 2015-12-08 11:40:02 -0600
Processing by PinsController#upvote as JS
Parameters: {"id"=>"10"}
Pin Load (0.2ms) SELECT "pins".* FROM "pins" WHERE "pins"."id" = ? LIMIT 1 [["id", 10]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 2]]
(0.3ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."voter_id" = ? AND "votes"."voter_type" = ? AND "votes"."vote_scope" IS NULL [["votable_id", 10], ["votable_type", "Pin"], ["voter_id", 2], ["voter_type", "User"]]
ActsAsVotable::Vote Load (0.6ms) SELECT "votes".* FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."voter_id" = ? AND "votes"."voter_type" = ? AND "votes"."vote_scope" IS NULL ORDER BY "votes"."id" DESC LIMIT 1 [["votable_id", 10], ["votable_type", "Pin"], ["voter_id", 2], ["voter_type", "User"]]
(0.2ms) begin transaction
(0.1ms) commit transaction
(0.2ms) SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."vote_flag" = ? AND "votes"."vote_scope" IS NULL [["votable_id", 10], ["votable_type", "Pin"], ["vote_flag", "t"]]
Rendered pins/upvote.js.erb (4.4ms)
Completed 200 OK in 25ms (Views: 9.4ms | ActiveRecord: 1.8ms)
I'm sure it's something really simple but ajax/js are even newer to me than rails.
Let me know if there's anything else I need to post. Any help will be so greatly appreciated!
Also for future reference, what would make the link load a page with the js code instead of executing the code? Since I don't feel like I changed anything that drastic today, I don't know how I got past that. I'm glad I did, but it would be helpful to know HOW.
It's doing that because your JS is technically targeting all the links with that class. Instead you could append the model's id of the individual pin to the link's class or create a data attribute but it's entirely up to you. In doing so it'll only target the one link that's clicked.
UPDATE:
Essentially you'll want to assign a class (instance's id) to a container div holding the vote button: pin-#{pin.id} for index view and pin-#{#pin.id} for show view.
Controller
def upvote
#pin.upvote_by current_user
respond_to do |format|
format.js { render "upvote.js.erb" }
end
end
Routes
...
resources :pins do
member do
put :upvote
end
end
Index View
...
%div{class: "btn-group pull-right pin-#{pin.id}"}
= render "upvote", pin: pin
Show View
...
.col-md-6
%div{class: "btn-group pull-right pin-#{#pin.id}"}
= render "upvote", pin: #pin
-if user_signed_in?
= link_to "Edit", edit_pin_path, class: "btn btn-default"
= link_to "Delete", pin_path, method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-default"
_upvote.html.haml
= link_to upvote_pin_path(pin), method: :put, remote: :true, class: "btn btn-default btn-like" do
%span.glyphicon.glyphicon-heart
= pin.get_upvotes.size
upvote.js.erb
$(".pin-<%= #pin.id %>").html("<%= escape_javascript(render 'upvote', pin: #pin) %>");

How do I return an error message with format.js and update my UI?

In my index.html.erb, I have this partial rendering like this:
<div class="card-comments">
<%= render partial: "nodes/comment", collection: node.comments.order(created_at: :desc) %>
</div>
That partial - _comment.html.erb - looks like this:
<div id="comment-<%= comment.id %>">
<%= comment.message %> | <%= comment.user.name %> | <%= time_ago_in_words(comment.created_at) %><br />
</div>
My CommentsController#Create action looks like this:
def create
#node = Node.find(params[:node_id])
#comment = current_user.comments.new(comment_params)
#comment.node = #node
#card_id = params[:card_id]
respond_to do |format|
if #comment.save and #node.save
format.js
else
format.js
end
end
end
As you can see, this just renders js only, so that calls this create.js.erb:
$("#<%= #card_id %> .card-comments").prepend("<%= j (render partial: 'nodes/comment', locals: { comment: #comment}) %>");
$("#card-input-field-<%= #card_id %>").val('');
This is my comment model with the rules:
class Comment < ActiveRecord::Base
validates_presence_of :message, message: "You can't submit an empty comment."
belongs_to :user
belongs_to :node, counter_cache: true
def type?
"Comment"
end
end
So all of that works wonderfully in the case when there is a valid comment (i.e. it doesn't invalidate any of my validation rules). However, I want to be able to handle errors gracefully.
When validation rule is violated, say entering a blank comment, it returns this error in the server.log but does nothing in the UI:
Started POST "/nodes/101/comments" for 127.0.0.1 at 2015-07-14 00:56:30 -0500
Processing by CommentsController#create as JS
Parameters: {"utf8"=>"✓", "comment"=>{"message"=>""}, "card_id"=>"card-2", "node_id"=>"101"}
User Load (4.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 57 ORDER BY "users"."id" ASC LIMIT 1
FamilyTree Load (1.0ms) SELECT "family_trees".* FROM "family_trees" WHERE "family_trees"."user_id" = $1 LIMIT 1 [["user_id", 57]]
Role Load (1.6ms) SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL))) [["user_id", 57]]
Node Load (1.1ms) SELECT "nodes".* FROM "nodes" WHERE "nodes"."id" = $1 LIMIT 1 [["id", 101]]
(1.1ms) BEGIN
(1.8ms) ROLLBACK
Rendered nodes/_comment.html.erb (21.5ms)
Rendered comments/create.js.erb (23.7ms)
Completed 500 Internal Server Error in 325ms (ActiveRecord: 51.2ms)
NoMethodError - undefined method `>' for nil:NilClass:
actionview (4.1.12) lib/action_view/helpers/date_helper.rb:74:in `distance_of_time_in_words'
actionview (4.1.12) lib/action_view/helpers/date_helper.rb:153:in `time_ago_in_words'
app/views/nodes/_comment.html.erb:2:in `_app_views_nodes__comment_html_erb___2666929257313190166_70115251186960'
actionview (4.1.12) lib/action_view/template.rb:145:in `block in render'
activesupport (4.1.12) lib/active_support/notifications.rb:161:in `instrument'
So, what I want to happen is, whenever an error occurs, I want it to tell the user in the UI (I guess in the create.js.erb) what the issue was.
How do I do that?
Use #comment or #node in create.js.erb to check if there are errors or not. Like to check validation error:
<% if #comment.errors.present? %>
//validation error change you ui here
<% else %>
//Success, change you ui here
<% end %>

How can I update an instance variable with each ajax request?

I have a long block of comments on a view of model Page. Instead of showing all the comments on page load, I'm trying to create a "view more" button that shows the next ten comments. The button sends an ajax request to the controller, which then renders this block using jquery:
_view_more.html.erb
<% comments.each_with_index do |comment, index|%>
<% if (( index > #start_number) && (index < #end_number) ) %>
<%= comment.text %>
<% end %>
Let's say I always want to show the next 10 comments. I would just set #start_number = #start_number + 10 and #end_number = #end_number + 10
in the controller, but instance variables get reset, so #start_number would be nil. How can I set a variable that increases by 10 upon every ajax request?
"view more" button
<%= link_to "view more", view_more_page_path, remote: true %>
pages_controller.rb
def view_more
#page = Page.find(params[:id])
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
view_more
$("#comments-body").append("<%= escape_javascript(render 'view_more') %>");
I will use haml and coffee-script
When rendering comments you put an html5 data attribute with the id of the comment:
#view where to render comments
%div#comments-wrapper{:"data-pageid" => #page.id}
=render #comments
=link_to "View more", "#", id: "view-more-link"
The comment partial
#comments/_comment.html.haml
%p.single-comment{:"data-commentid" => comment.id}
=comment.body
application.coffee
$ ->
$("#view-more-link").on 'click', ->
last_comment_id = $("#comments-wrapper .single-comment").last().data('commentid')
page_id = $("#comments-wrapper").data("pageid")
$.ajax
url: "/comments/view_more"
dataType: "script"
data:
last_comment_id: last_comment_id
page_id: page_id
comments_controller
def view_more
#page = Page.find(params[:pageid])
if params[:last_comment_id]
#comments = #page.comments.where("comments.id > ?", params[:last_comment_id]).limit(10)
end
respond_to do |format|
format.js
end
end
comments/view_more.js.erb
$("#comments-wrapper").append("<%= escape_javascript(render #comments) %>");
Note: I don't how your routes were set up so I put the page.id as a data-attribute as well
I would use already implemented pagination gems kaminari or will_paginate. I'll create this example using will_paginate.
First of all, it's important to say that your approach is incorrect, because it loads all comments every view_more request. If you want to show 10 comments, makes sense select only they from database, right? The pagination gem will do it for you!
Let's to the code:
"view more" button
<%= link_to "view more", view_more_page_path, remote: true, id: 'view-more-btn' %>
pages_controller.rb
def view_more
#comments = Page.find(params[:id]).comments.paginate(page: params[:page], per_page: 10)
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
_view_more.html.erb
<% #comments.each do |comment| %>
<%= comment.text %>
<% end %>
view_more.js.erb
$("#comments-wrapper").append("<%= escape_javascript(render 'view_more') %>");
# We need to update the 'view more' link with the next page number
$('#view-more-btn').attr('href', '<%= view_more_page_path((params[:page] || 0) + 1) %>')
is it not good to update an hidden variable before making ajax call with the count..?
var currentVal = parseInt($("[type=hidden]").val());
$("[type=hidden]").val( currentVal + 1 );
add the hidden field right at the begining of the comments section with default value as "0"
<input type="hidden" name="hiddenId" id="hiddenId" value="0">
Hope it will help
If you want a quick and dirty approach, you could save start_number and end_number inside a cookie.
But keeping track of what needs to be rendered next on client side would be a right thing to do.

Creating Rails 4 Form with Join Table Metadata

Very new Rails 4 developer here. I've got a form where a user is creating Exercises. Exercises can have many Equipment, and Equipment can be optional( think push-up stands for doing push-ups ). I store this "optional" field on the join table exercise_equipment.
I cannot get the parameters to actually send through the values of the collection element that I pick. See below for the model, view, controller, and parameters.
Here are the attributes/relationships of my models:
# id :integer
# name :string
# is_public :boolean
Exercise
has_many :exercise_equipment
has_many :equipment, :through => :exercise_equipment
accepts_nested_attributes_for :exercise_equipment
# id :integer
# exercise_id :integer
# equipment_id :integer
# optional :boolean
ExerciseEquipment
belongs_to :exercise
belongs_to :equipment
accepts_nested_attributes_for :equipment
# id :integer
# name :string
Equipment
has_many :exercise_equipment
has_many :exercises, :through => :exercise_equipment
Here are some (maybe) relevant controller methods:
def new
#exercise = Exercise.new
#exercise.exercise_equipment.build
end
def create
#exercise = Exercise.new( exercise_params )
if #exercise.save
redirect_to #exercises
else
render 'new'
end
end
def edit
#exercise = Exercise.find( params[:id] )
end
def update
#exercise = Exercise.find( params[:id] )
if #exercise.update_attributes( exercise_params )
redirect_to #exercises
else
render 'edit'
end
end
def exercise_params
params.require( :exercise ).permit(
:name,
:is_public,
exercise_equipment_attributes: [
:id,
:optional,
equipment_attributes: [
:id,
:name
],
]
)
end
This is my shot at creating a view to do what I want:
exercises/new.html.erb
<%= form_for #exercise do |f| %>
<%= render 'form', f: f %>
<%= f.submit "New Exercise" %>
<% end %>
exercises/_form.html.erb
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.check_box :is_public %> Public
<%= f.fields_for( :exercise_equipment ) do |eef|
<%= eef.fields_for( :equipment ) do |ef|
ef.collection_select :id, Equipment.all, :id, :name %>
<% end %>
<%= eef.check_box :is_optional %> Optional
<% end %>
When I put all of this together and submit an update to an already-existing exercise, the values all go through the params hash, but aren't changed to the new values I've selected...
Parameters: {
"utf8"=>"[checkbox]",
"authenticity_token"=>"[token]",
"exercise"=>{
"name"=>"Test",
"is_public"=>"1",
"exercise_equipment_attributes"=>{
"0"=>{
"equipment_attributes"=>{
"id"=>"1"
},
"optional"=>"1",
"id"=>"2"
}
}
},
"commit"=>"Save Exercise",
"id"=>"1"
}
If you can help me out, I'd be super appreciative. Just let me know if you need any more information and I can provide it.
EDIT
Here is the state of the database before updating:
postgres#=>db=# select id, name, is_public from exercises;
id | name | is_public
----+------+-----------
2 | Test | t
(1 row)
Time: 61.279 ms
postgres#=>db=# select id, exercise_id, equipment_id, optional from exercise_equipment;
id | exercise_id | equipment_id | optional
----+-------------+--------------+----------
2 | 2 | 1 | t
(1 row)
Time: 58.819 ms
postgres#=>db=# select id, name from equipment where id = 1;
id | name
----+-------------
1 | Freeweights
(1 row)
I then go to the update route for that exercise, select a different equipment from the collection, and submit the form. I get the following Rails Console results:
Started PATCH "/exercises/system-test" for 127.0.0.1 at 2014-08-12 23:48:18 -0400
Processing by ExercisesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"PsbbUPSCiIew2Fd22Swn+K4PmLjwNDCrDdwXf9YBcm8=", "exercise"=>{"name"=>"Test", "is_public"=>"1", "exercise_equipment_attributes"=>{"0"=>{"equipment_attributes"=>{"id"=>"1"}, "optional"=>"1", "id"=>"2"}}}, "commit"=>"Save Exercise", "id"=>"system-test"}
Exercise Load (60.5ms) SELECT "exercises".* FROM "exercises" WHERE "exercises"."slug" = 'system-test' ORDER BY "exercises"."id" ASC LIMIT 1
(57.3ms) BEGIN
ExerciseEquipment Load (76.2ms) SELECT "exercise_equipment".* FROM "exercise_equipment" WHERE "exercise_equipment"."exercise_id" = $1 AND "exercise_equipment"."id" IN (2) [["exercise_id", 2]]
Equipment Load (59.1ms) SELECT "equipment".* FROM "equipment" WHERE "equipment"."id" = $1 LIMIT 1 [["id", 1]]
User Load (60.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 10]]
Exercise Exists (60.5ms) SELECT 1 AS one FROM "exercises" WHERE ("exercises"."name" = 'Test' AND "exercises"."id" != 2 AND "exercises"."user_id" = 10) LIMIT 1
(64.8ms) COMMIT
Redirected to http://localhost:3000/exercises/system-test
Completed 302 Found in 590ms (ActiveRecord: 580.0ms)
Started GET "/exercises/system-test" for 127.0.0.1 at 2014-08-12 23:48:19 -0400
Processing by ExercisesController#show as HTML
Parameters: {"id"=>"system-test"}
Exercise Load (64.1ms) SELECT "exercises".* FROM "exercises" WHERE "exercises"."slug" = 'system-test' ORDER BY "exercises"."id" ASC LIMIT 1
Equipment Load (58.7ms) SELECT "equipment".* FROM "equipment" INNER JOIN "exercise_equipment" ON "equipment"."id" = "exercise_equipment"."equipment_id" WHERE "exercise_equipment"."exercise_id" = $1 [["exercise_id", 2]]
Rendered exercises/show.html.erb within layouts/application (122.7ms)
User Load (60.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 10 ORDER BY "users"."id" ASC LIMIT 1
Rendered shared/_header.html.erb (61.9ms)
Rendered shared/_alerts.html.erb (0.1ms)
Completed 200 OK in 264ms (Views: 21.3ms | ActiveRecord: 240.8ms)
Firstly, you need to make sure you define your associations correctly.
Any has_many association should be defined with a plural name -
#app/models/exercise.rb
Class Exercise < ActiveRecord::Base
has_many :exercise_equipments
has_many :equipments, :through => :exercise_equipments
accepts_nested_attributes_for :exercise_equipments
end
#app/models/exercise_equipment.rb
Class ExerciseEquipment < ActiveRecord::Base
belongs_to :exercise
belongs_to :equipment
end
#app/models/equipment.rb
Class Equipment < ActiveRecord::Base
has_many :exercise_equipments
has_many :exercises, through: :exercise_equipments
end
If you've already got it working, and are happy with what you've got, then I'd recommend keeping your current setup. However, you may wish to adopt the above for convention's sake
Edit I see from the deleted answer that Beartech investigated this, and turns out Rails treats Equipment / Equipments as the same. Will be worth ignoring the above, but I'll leave it for future reference
Params
I cannot get the parameters to actually send through the values of the
collection element that I pick. See below for the model, view,
controller, and parameters.
I think I get what you mean - you're looking to update the record, but it does not send through the updated parameters to your controller, hence preventing it from being updated.
Although I can't see any glaring problems, I would recommend the issue is that you're trying to populate the exercise_id of an Exercise object. You need to define it for the exercise_equipment object:
<%= f.fields_for :exercise_equipment do |eef| %>
<%= eef.collection_select :equipment_id, Equipment.all, :id, :name %>
<%= eef.check_box :is_optional %>
<% end %>
This will populate your exercise_equipment table as described here:
Time: 61.279 ms
postgres#=>db=# select id, exercise_id, equipment_id, optional from exercise_equipment;
id | exercise_id | equipment_id | optional
----+-------------+--------------+----------
2 | 2 | 1 | t
(1 row)
Currently, you're populating the Equipment model with equipment_id - which won't work. Populating the model in that way will server to create a new record, not update the ones already created
Extra Field
I want to have a link to add an additional equipment field when it is
clicked, similar to how Ryan Bates did it in this RailsCast, but the
helper method he writes( see "Show Notes" tab if you're not subscribed
to see the source ) seems to become substantially more complex when
dealing with the nested views shown in my code below. Any help in
dealing with this?
This a trickier mountain to overcome
Ryan uses quite an outdated method in this process (to pre-populate the link and then just let JS append the field). The "right" way is to build a new object & append the fields_for from ajax. Sounds tough? That's because it is :)
Here's how you do it:
#config/routes.rb
resources :exercises do
collection do
get :ajax_update #-> domain.com/exercises/ajax_update
end
end
#app/models/exercise.rb
Class Exercise < ActiveRecord::Base
def self.build
exercise = self.new
exercise.exercise_equipment.build
end
end
#app/controllers/exercises_controller.rb
Class ExercisesController < ApplicationController
def new
#exercise = Exercise.build
end
def ajax_update
#exercise = Exercise.build
render "add_exercise", layout: false #> renders form with fields_for
end
end
#app/views/exercises/add_exercise.html.erb
<%= form_for #exercise do |f| %>
<%= render partial: "fields_for", locals: { form: f } %>
<% end %>
#app/views/exercises/_fields_for.html.erb
<%= f.fields_for :exercise_equipment, child_index: Time.now.to_i do |eef| %>
<%= eef.collection_select :equipment_id, Equipment.all, :id, :name %>
<%= eef.check_box :is_optional %>
<% end %>
#app/views/exercises/edit.html.erb
<%= form_for #exercise do |f| %>
<%= render partial: "fields_for", locals: { form: f } %>
<%= link_to "Add Field", "#", id: "add_field" %>
<% end %>
#app/assets/javascripts/application.js
$(document).on("click", "#add_field", function() {
$.ajax({
url: "exercises/ajax_update",
success: function(data) {
el_to_add = $(data).html()
$('#your_id').append(el_to_add)
}
});
});

Categories

Resources