通过模型关联更新 rails 属性

Updating a rails attribute through a model association

我有两个模型 shopuser。商店 has_many 用户和用户 has_one 商店。我正在尝试在 shop/show 上创建一个按钮,允许用户选择其商店。该按钮应将参数 shop_id 发送到 Users_Controller#update_shop,然后将 User.shop_id 更改为页面上商店的 ID。

Users_Controller#update_shop中的当前方法如下:

def update_shop
  @user = User.find(params[:id])
  @user.update_attributes(shop_id: params[:shop][:id])
  flash[:success] = "Added Shop!"
end

show/shop 上的按钮是这样的:

  <%= form_for User.update_shop, remote: true do |f| %>
    <%= f.hidden_field :shop_id, value: @shop.id %>
    <%= f.submit 'Add As Your Shop', :class => 'button blue-button' %>
  <% end %>

我收到 #` 的错误 NoMethodError in ShopsController#show undefined methodupdate_shop'。不过,该方法是在用户控制器中定义的。

我知道可能有一种更有效的方法来通过协会更新 User.shop_id,因此非常感谢有关这样做或让它起作用的提示。

我认为最好用 link 和 POST 方法代替表单:

<%= link_to 'Add As Your Shop', update_shop_url(id: @user.id, shop_id: @shop.id, class: 'button blue-button', data: { method: 'post' } %>

使用此设置,您还应该更改控制器方法:

def update_shop
  ...
  @user.update_attributes(shop_id: params[:shop_id])
  ...
end