I'm building a simple Reviewer Blog Post on Rails 5 in order to teach myself. Its a Video Game Reviewer where Users can write Reviews about recent Games they've played. Users can also add Comments to Reviews.
I want to implement a custom attribute writer on my Game model through nested forms. When a User lists a Game for the first time, I also want them to be able to write a Review for that Game on the spot.
Game.rb
class Game < ApplicationRecord
has_many :reviews, dependent: :destroy
has_many :users, through: :reviews
validates :title, presence: true
def reviews_attributes=(reviews_attributes)
reviews_attributes.values.each do |review_attributes|
self.reviews.build(review_attributes)
end
end
end
games/new.html.erb
<h1>Enter a new Game</h1>
<%= form_for @game do |f| %>
<%= render 'shared/error_messages', object: @game %>
<%= render 'new_form', f: f %>
<br><br>
Review:
<br>
<%= f.fields_for :reviews, @game.reviews.build do |r| %>
<%= render 'reviews/form', f: r %>
<%= f.submit "Add Game and/or Review!" %>
<% end %>
<% end %>
Reviews/form partial
<%= f.label :title %>
<%= f.text_field :title %>
<br>
<%= f.label :content %>
<%= f.text_area :content %>
<br>
<%= f.label :score %>
<%= f.text_field :score %>
<%= f.hidden_field :user_id, :value => current_user.id %>
Games_Controller.rb
def create
@game = Game.new(game_params)
if @game.save
redirect_to @game
else
render :new
end
end
private
def game_params
params.require(:game).permit(:title, :platform, reviews_attributes: [:rating, :content, :user_id])
end
For some reason I keep getting Reviews is invalid whenever I try to create a new Review associated with a Game through my nested forms. My error_messages partial is rendering the error message saying: "1 error prohibited this from being saved: Reviews is invalid".
Something about the Review forms or data in the params hash isn't being transmitted I guess. I am not sure why. I even tried building the associations with the built-in Rails helper: accepts_nested_attributes_for and I still get the same error.
Here is the link to my repo for full clarity: https://github.com/jchu4483/Rails-Assessment-
Thanks, and any help or advice is appreciated.