JiaPing
JiaPing

Reputation: 119

ruby - NoMethodError: undefined method `status'

I want to make a button which when clicked should change its status.(open <=> stop). However I have no idea, how to get the values of status. When I ran this code =>

@project.project_users.status = [email protected]_users.status # flop the status

It appeared !! #<NoMethodError: undefined method 'status' for #<ProjectUser::ActiveRecord_Associations_CollectionProxy:0x007feb80dcb540>>. Can somebody give me some methods to get @project.project_users.status? Thank you!

controllers/project_users_controller.rb

def flog
    @project.project_users.status = [email protected]_users.status # flop the status
    @project_user.save
    redirect_to project_project_user_path(project_user)
end

views/project_users/show.html.erb

<%= link_to (@project_user.status ? "open" : "stop"), flog_project_project_user_path(@project, @project_user) %>

config/routes.rb

resources :projects, only:[:index, :show, :new, :create, :mypage] do
resources :project_users, only:[:index, :show, :create] do
    member do
      get :flog
    end
end

models/project_user.rb

    enum status: { open: 1, stop: 2, hidden: 3, closed: 9 }

Upvotes: 0

Views: 1283

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

There are multiple issues here. First and foremost, you are trying to call an instance method on a collection of project_users - which is why you're seeing that error.

You would need to instead do something like:

@project.project_users.each do |project_user|
  project_user.status = !project_users.status
end

...Or maybe you can just access one of the collection like:

@project.project_user.status = [email protected]_user.status

...Or maybe what you actually intended here was:

@project_user.status = !@project_user.status

...But even that won't work, because you have defined status as an enum not a boolean. If you want to toggle the status between open and stop, then you'll need to write this in the code. (And also decide how to handle situations where the status is hidden/closed.)

By the way, if status was a boolean then you could use the built-in method: project_user.toggle!(:status) here.

You are also inconsistently using the word flog(??!) instead of flop for the route/controller action; you should probably fix that.

Upvotes: 2

Related Questions