Rails 4查看并更新has_many的所有表单

时间:2014-03-07 11:04:01

标签: ruby-on-rails ruby-on-rails-4

我是rails的新手,目前正在开发一个简单的考勤数据库。最初我使用了has_and_belongs_to_many关系,但由于我现在需要跟踪其他信息并快速更新所有记录,我将用has_many through模型替换它。

声明目前如下所示:

class User < ActiveRecord::Base
  has_many :registrations
  has_many :events, through: :registrations
end

class Registration < ActiveRecord::Base
  belongs_to :users
  belongs_to :events
end

class Event < ActiveRecord::Base
 has_many :registrations
 has_many :users, through: :registrations
end

注册还有一个'status'字符串字段,允许'Yes','No'和'Maybe'响应。

我目前正在尝试构建一个循环遍历所有事件的表单,每个事件显示所有用户及其响应到目前为止。像这样:

Event 1
John  Yes()  No()  Maybe()  No Response(*)
Anne  Yes(*)  No()  Maybe()  No Response()
Mike  Yes(*)  No()  Maybe()  No Response()

Event 2
John  Yes(*)  No()  Maybe()  No Response()
Anne  Yes()  No()  Maybe(*)  No Response(*)
Mike  Yes()  No()  Maybe(*)  No Response(*)

Event 3
John  Yes()  No()  Maybe()  No Response(*)
Anne  Yes()  No()  Maybe()  No Response(*)
Mike  Yes()  No()  Maybe()  No Response(*)

[Submit]

当我基于使用HABTM的单个响应构建它时,simple_form仅使用'f.association'来处理它,但我甚至不确定从哪里开始使用我的控制器和视图。

感谢任何回复,甚至只是我希望前进的一般方向的提示。

1 个答案:

答案 0 :(得分:0)

  1. 使用状态机
  2. 通过访问

  3. 状态机

    刚刚看到你有这个设置(但我会保留,因为我已经在写了)

    可能state machine中受益。这基本上允许您拥有一个列(称为statestatus),并将使用一组用户定义的方法更新其值:

        #app/models/registration.rb
    state_machine :initial => :maybe do
    
        #States
        state :no
        state :yes
        state :maybe
    
        #Attend
        event :will_attend do
            transition :all => :yes
        end
    
        #No
        event :will_not_attend do
            transition :all => :no
        end
    
    end
    

    这可能超出您的使用范围,但希望能够深入了解您可以做什么


    访问

    您问题的真正答案是使用accepts_nested_attributes_for或直接访问join model

    class User < ActiveRecord::Base
      has_many :registrations
      has_many :events, through: :registrations
    end
    
    class Registration < ActiveRecord::Base
      belongs_to :users
      belongs_to :events
    end
    
    class Event < ActiveRecord::Base
     has_many :registrations
     has_many :users, through: :registrations
    end
    
    #config/routes.rb
    resources :events do 
       get "register", to: "registrations#new" #-> app/events/:event_id/register
       post "register", to: "registrations#create" #-> app/events/:event_id/register
    end
    
    #app/controllers/registrations.rb
    def new
         @registration = Registration.new
    end
    
    def create
         @registration = Registration.new(registration_params)
    end
    
    private
    
    def registration_params
        params.require(:registration).permit(:status).merge({user_id: current_user.id, event_id: params[:event_id]})
    end
    
    #app/views/registrations/new.html.erb
    <%= form_for @registration do |f| %>
        <%= f.radio_button :status,  "Yes" %>
        <%= f.radio_button :status, "No" %>
        <%= f.radio_button :status, "Maybe" %>
    <% end %>