Rails AJAX更新嵌套模型的麻烦

时间:2014-01-17 21:36:45

标签: ruby-on-rails ajax forms model

我有一个模型Game,Square,Ownedsq和User的应用程序,我正在尝试更新游戏中的方块:user_id。我现在已经尝试了几个小时,我相信模型关系是正确的,我只是错过了一些小的东西,所以我感谢任何帮助。

目前单击更新的ownedsq提交按钮不会更改user_id。没有错误,没有任何更新,服务器上没有任何反应。

游戏/ show.html.erb (10 Ownedsq行)

<div class="squareBoard">
    <% @ownedsqs.each_slice(10) do |slice| %>
        <div class='row'>
            <% slice.each do |s| %>
                <%= div_for s, class: 'sq' do |buy| %>
                    <%= s.user_id %>
                    <%= render "buyownedsq", s: buy %>
                <% end %>
            <% end %>
        </div>
    <% end %>
</div>

_buyownedsq.html.erb (点击将ownsq user_id设置为当前用户)

<%= simple_fields_for s, remote: true do |z| %>
    <%= z.input :user_id, as: :hidden, input_html: {value:current_user.id} %>
    <%= z.button :submit %>
<% end %>

games_controller.rb

def show
    require 'enumerator'
    @user = current_user
    @game = Game.find(params[:id])
    @squares = Square.all
    @square = Square.find(params[:id])
    @ownedsqs = Ownedsq.all
end

ownedsqs_controller.rb

def update
    @ownedsq.find(params[:id])

    respond_to do |format|
        format.js
        if @ownedsq.update_attributes(params[:ownedsq])
            format.html {redirect_to game_path}
            format.json {head :no_content}
        else
            format.html {redirect_to :back}
        end  
    end 
end

Game.rb

has_many :ownedsqs
has_many :squares, through: :ownedsqs
has_and_belongs_to_many :users

accepts_nested_attributes_for :ownedsqs
accepts_nested_attributes_for :squares

Square.rb

has_many :ownedsqs
has_many :users, through: :ownedsqs
has_many :games, through: :ownedsqs

accepts_nested_attributes_for :ownedsqs
accepts_nested_attributes_for :users
accepts_nested_attributes_for :games

Ownedsq.rb

belongs_to :square
belongs_to :user
belongs_to :game

validates_uniqueness_of :square_id, scope: :game_id

User.rb

has_and_belongs_to_many :games
has_many :ownedsqs
has_many :squares, through: :ownedsqs

accepts_nested_attributes_for :ownedsqs
accepts_nested_attributes_for :squares

1 个答案:

答案 0 :(得分:0)

这里有几个问题供您查看:

  1. 您如何收到params[:id]的{​​{1}}?
  2. 您可以轻松摆脱视图级ownedsq参考
  3. 您的远程通话不会直接引发错误;他们将通过浏览器的user_id标签进行操作

  4. <强>格式

    我只是使用一个简单的链接/按钮将请求发送到服务器:

    network

    这将向服务器发送请求,您可以按如下方式处理:

    _buyownedsq.html.erb
    <%= button_to ownedsq_path(buy.id), method: :put, data: {confirm: "Are you sure?"}, remote: :true %>
    

    保存

    您的关联看起来正确 - 我不认为#app/controllers/ownedsqs_controller.rb def update @ownedsq = Ownedsq.find(params[:id]) #where do you get the params[:id] var? respond_to do |format| format.js if @ownedsq.update_attributes(user_id: current_user.id) format.html {redirect_to game_path} format.json {head :no_content, status: :200} else format.html {redirect_to :back} format.json {status: :500 } end end end 方法会混淆/有问题,因为您直接使用update_attributes模型(不使用OwnedSq等)