veritas1
veritas1

Reputation: 9190

Rails 3.0.10 AJAX issue, create.js.erb file

I'm new to web development so bear that in mind.

I'm creating my first app using Rails 3.0.10

I have a micropost form that I'm trying to implement AJAX into.

I have set up the controller correctly(I believe) and have added :remote => true to the micropost form.

Microposts Controller

def create
      @user = User.find(current_user.id)
      @micropost = current_user.microposts.build(params[:micropost])
      if @micropost.save
        flash[:success] = "Created micropost"
        respond_to do |format|
        format.html { redirect_to @user }
        format.js
      end
      else
        render 'users/show'
      end
    end

The problem is in the create.js.erb file, in views/microposts

As a test, if I put

$("#microposts").html("<p>Hello world!</p>")

it works as expected.

Even if I embed ruby code into it with an instance variable, that works too.

But, if I put

$("#microposts").html("<%= render @microposts %> ")

it does nothing.

In fact, as soon as I try any rails method, it does nothing.

These are my javascript files that are included:

/javascripts/jquery.js
/javascripts/jquery_ujs.js
/javascripts/jquery.min.js
/javascripts/application.js

Any help would be greatly appreciated, I have been stumped for little while now.

Upvotes: 3

Views: 968

Answers (2)

Callmeed
Callmeed

Reputation: 5002

You're not loading @microposts (the collection) in the create action.

So, you need to either need to set it via something like:

@microposts = current_user.microposts

But there's really no need to do another DB call. I'd recommend just appending (or prepending) your #microposts element with the new item. Something like:

$("#microposts").prepend("<%= escape_javascript(render '_micrpost_item') %>");

And that partial should be able to use the @micropost object from the create action.

Upvotes: 2

prusswan
prusswan

Reputation: 7101

Try this instead:

$("#microposts").html("<%= escape_javascript(render @microposts) %> ");

Upvotes: 0

Related Questions