2016-09-22 39 views
0

我正在构建一个简单的Reviewer Blog Post on Rails 5,以便自学。它是一个视频游戏评论家,用户可以在其中撰写有关他们最近玩过的游戏的评论。用户还可以将评论添加到评论。以嵌套形式自定义属性设置器方法

我想通过嵌套窗体在我的游戏模型上实现自定义属性编写器。当用户首次列出游戏时,我也希望他们能够当场为该游戏撰写评论。

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 

游戏/ 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 %> 

评价/形成局部

<%= 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 

出于某种原因,我不断收到评论是无效的,每当我试图创建通过我的嵌套形式与游戏相关的新的评论。我的error_messages部分显示错误消息:“1个错误禁止保存:评论无效”。

关于评论形式或params散列中的数据的东西没有被传输我猜。我不知道为什么。我甚至尝试用内置的Rails帮助程序构建关联:accepting_nested_attributes_for并且我仍然得到相同的错误。

这里是链接到我的回购完全清晰:https://github.com/jchu4483/Rails-Assessment-

谢谢,任何帮助或建议表示赞赏。

+0

尝试在你的强参数中添加':id'到'reviews_attributes':'reviews_attributes:[:id,:rating,:content,:user_id]' – Ren

+0

我刚刚尝试过,它给了我同样的错误。 –

回答

0

现在我认为这个问题可能是因为与has_manythrough关联的嵌套窗体。您的评论没有通过验证,因为它也加入了用户模型。您的评论模型应该有accepts_nested_attributes_for用户

class Review < ApplicationRecord 
    belongs_to :user 
    belongs_to :game 

    accepts_nested_attributes_for :user 
end 

和你形成应该有另一个fields_for用户

<%= form_for @game do |f| %> 
    <%= f.fields_for :reviews do |r| %> 
     <%= r.fields_for :users do |u| %> 
     ... 
     <% end %> 
    <% end %> 
    <%= f.submit %> 
<% end %> 

,并在你的game_params控制器,你需要传递的users_attributes数组太

def game_params 
    params.require(:game).permit(:title, :platform, reviews_attributes: [:id, :rating, :content, :user_id, user_attributes: [...]) 
end 

回答此SO问题可能会有所帮助:https://stackoverflow.com/a/21983998/5531936

+0

我也试过,仍然是一样的错误。 –

+0

这个错误会给你一个源文件和代码行号吗?你能说出错误是指什么吗? – Ren

+0

实际上,没有ActiveRecord或Rails错误,我的error_messages部分显示错误消息:“1个错误禁止保存:评论无效”。关于评论形式或params散列中的数据的东西我没有被传送。 –

1

它看起来像game_params中的reviews_attrbitues中的属性与表单上的属性不匹配。 Game_params列出评级,内容,user_id。在表格中您有标题,内容,分数。