RoR:在不同的控制器中使用用户模型中定义的方法



我是RoR的新手,希望你们专家能在这方面帮助我。如果我的问题听起来很奇怪或愚蠢,请提前道歉。如果您需要更多说明,请告诉我,提前非常感谢。

我在用户模型中有一个名为 is_pollie(将默认值设置为 false(的布尔方法,一旦用户在名为 profiles_controller.rb 的不同控制器中完成表单,我想将其更改为 true。

现在,我有一个具有定义方法的用户模型:

class User < ApplicationRecord
has_many :profiles
def self.is_pollie?
is_pollie
end

在一个名为 profiles_controller.rb 的不同控制器中:

class ProfilesController < ApplicationController
before_action :authenticate_user!, except: [:show]
def create
@pollie = User.is_pollie?
@profile = current_user.profiles.build(profile_params)
if @profile.save
  # what should I put here if I want the is_pollie? to change to true upon
  a user click the save button on the form? 
  redirect_to basic_profile_path(@profile)
else
  flash[:alert] = "Oh no, something went wrong."
  render :new
end
end

在表单所在的页面中:

<%= form_for @profile do |f| %>
<div class="form-group">
<label>Displayed name:</label>
<%= f.text_field :display_name,class: "form-control"%>
</div>
<%= f.submit "Save", class: "btn-submit" %>
<% end %>

希望您理解我的问题并能够提供帮助。再次非常感谢。

你可以试试:

current_user.update(is_pollie: true)

顺便说一句,其他几点...

这:

class User < ApplicationRecord
  has_many :profiles
  def self.is_pollie?
    is_pollie
  end
end

没有任何意义,因为self is_pollie?类方法。但是,is_pollie是一个实例值。

此外,您甚至不需要is_pollie?因为您可以使用 do current_user.is_pollie 这将返回true false .

最后,您没有在任何地方使用@pollie = User.is_pollie?,那么为什么要这样做呢?

使用 current_user.update_column(:is_pollie, true)

更新方法将触发call_backs,建议使用 update_column 来更新所选属性。

对于倍数,您可以使用update_columns(attributes1: value, attributes2: value)

最新更新