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