Rails - How do I refresh a page without reloading

2019-07-06 17:05发布

问题:

This question is about problems I ran into after asking my previous question Rails - How do I refresh a page without reloading it?

Have been googling but cannot find a solution.

I'm building a function that gives out a random record every time people go to that page but the random record will change again if the user refresh the page.

Therefore I have tried using cookies

#posts_controller.rb    

def new
  @random = cookies[:stuff] ||= Stuff.random
end

and call @random.content in my posts/new view since I want only the content of the Stuff model, when I go to the page for the first time is fine but when I refresh the page, it gives me this error

undefined method 'content' for "#<Stuff:0x0000010331ac00>":String

Is there a way to resolve this?

Thanks!

----Update----

I have fixed the content missing problem using <%= show_random(@random)['content'] %> and the Internal Server Error expected Hash (got Array) for param 'post'using

<%= f.hidden_field :stuff_id , :value => show_random(@random)[:id] %>

stuff/new.html.erb

# app/views/stuff/new.html.erb

<%= show_random(@random)[:content] %>

      <div>
        <%= f.hidden_field :stuff_id , :value => show_random(@random)[:id] %><br>
      </div> 

But when creating the Post without meeting the validation, it gives me

no implicit conversion of Stuff into String

Extracted source (around line #2):

1
2  <%= show_random(@random)['title'] %>

I think it has something to do with my create action in my Posts_controller.erb

Please have a look below of my Posts_controller.erb

  def create
    @post = current_user.posts.build(post_params)
    if @post.save
      flash[:success] = "Post created successfully!"
      else
      @random = Stuff.where(id: params[:post][:stuff_id]).first
      render 'new'
    end
  end

回答1:

The first time , as cookies[:stuff] is null, so a new Stuff instance is assigned to both cookies[:stuff] and @random, so the content method call on @random will be fine. But as you store an object into the cookies[:stuff], the value will be converted into a string by rails automatically.

The second time, you visit the page, the cookies[:stuff] is not empty, and is assigned to the @random variable. But as previous saying, the content inside the cookies is a string, so calling content method on a string can not work.



回答2:

Make your .random method defined on Stuff return a serialized record, which you can then deserialize in your views (possibly with a helper method) to make it a hash:

# app/models/stuff.rb
def self.random
  random_record_magic.to_json
end
end

# app/views/stuff/index.html.erb
<%= show_random(@random)['content'] %>

# app/helpers/stuff_helper.rb
def show_random(random)
  JSON.parse(random)
end