Reputation: 11251
I have read all answers for this topic, but I beg your help bc I still haven't find a solution. I create vote counter that will read from model increase likes counter and write updated counter++ to model.
I have index.html.erb
<div class="row">
<div id="tasks"><%= render @like %></div>
</div>
<div class="row">
<div id="like-form"></div>
</div>
<div class="col-md-2 col-md-offset-4">
<%= link_to new_like_path, remote: true do %>
<button class="btn btn-default">New</button>
<% end %>
</div>
model schema:
create_table "likes", force: true do |t|
t.string "count"
t.datetime "created_at"
t.datetime "updated_at"
end
I have LikesController
def new
if Like.first.count.to_i >= 0
then Like.create(count: "0")
end
@like = Like.first.count.to_i
@like++
Like.update(0, :count => @like.to_s)
end
new.js.rb
file
$('#like-form').html("<%= j (render 'form') %>");
$('#like-form').slideDown(350);
And I have _form.html.erb
<%= @like %>
It doesn't want to render and I got
'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
I am pretty new in rails, hope it all makes sense. I have heard about different ways to implement this task, but please help me to fix provided approach: to render form w/ ruby variable to html.
Upvotes: 2
Views: 62
Reputation: 659
You do not have to render an instance variable, you can write:
<div id="tasks"><%= @like %></div>
Also, your count column should be of type integer. If the count column is of type integer you can set the default value to 0 in your database. Here are the steps to go about doing this:
In your migration file add:
remove_column :likes, :count, :integer
add_column :likes, :count, :integer, default: 0
Then run rake db:migrate
in your console
Since your count
column is now of type integer and the default value of this column is now 0. You can change your new
action in your controller to:
@like = Like.create
@like.increment!(:count)
Rails has an increment method you can use. Also you should reference what you are trying to like, I don't know how this code is of any use if you're not liking something.
I don't understand what you are trying to achieve with:
$('#like-form').html("<%= j (render 'form') %>");
$('#like-form').slideDown(350);
But if you are just trying to update your likes, you can just write:
$("div#tasks).text(<%= j(@like) %>);
If you can describe what you are trying to achieve I can help you more.
Upvotes: 1