Rails - 数组

时间:2015-07-22 22:59:20

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

我有一个管理控制器来创建“位置”,其中包含一个表单。在表单中,您可以创建一个新的“位置”,并为其命名,描述和“退出”。

<%= form_for @location do |f| %>
    <p>
        <%= f.label :name %><br>
        <%= f.text_field :name %>
    </p>

    <p>
        <%= f.label :description %><br>
        <%= f.text_area :description %>
    </p>

    <p>
        Exits:
        <br/>
        <% @locations.each do |e| %>
            <%= f.label :locations %>
            <%= f.check_box :locations %>
        <% end %>
    </p>

    <p>
        <%= f.submit %>
    </p>
<% end %>

@locations是设置为“退出”的所有可用位置。我正在尝试使用复选框在新位置内创建一系列位置,以检查它们是否应设置为“退出”,但不确定如何继续,因为我只是在教自己而且是第一天。

我也想知道如何在Location模型中设置“退出”。现在我有:

class Location < ActiveRecord::Base
    has_many :locations
    validates :name, presence: true, length: { minimum: 1 }
    validates :description, presence: true
end

创建时:

class CreateLocations < ActiveRecord::Migration
  def change
    create_table :locations do |t|

      t.string :name
      t.text :description
      t.references :location, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

但我想将它们称为“退出”而非“位置”(即Location.exits而不是Location.locations)。

更新

我已更新表单以使用collection_check_boxes帮助程序

<%= f.collection_check_boxes(:exit_ids, @locations, :id, :name) do |cb| %>
    <%= cb.label %> <%= cb.check_box %> <br/>
<% end %>

所以我现在在创建动作中有这个

    def create
        @location = Location.new(location_params)

        if @location.save
            params[:location][:exit_ids].each do |e|
                if e.to_i > 0
                    tempLocation = Location.find(e.to_i)
                    @location.allowExitTo(tempLocation)
                end
            end
            redirect_to @location
        else
            render 'new'
        end
    end

允许退出:

def allowExitTo(other_location)
    exit_locations.create(to_id: other_location.id)
end

使用以下方式创建退出关系:

class Exit < ActiveRecord::Base
    belongs_to :from, class_name: 'Location'
    belongs_to :to, class_name: 'Location'

    validates :from_id, presence: true
    validates :to_id, presence: true
end

希望我走在正确的轨道上。它似乎有效,所以我猜是这样。

1 个答案:

答案 0 :(得分:0)

编辑:对不起,我一定有脑屁什么的。你不是在做一个简单的有多少和属于你的关系,你想要一个多与多对多的关系。这比我知道如何解释更复杂。但是这个答案很好地解释了这一点:Many-to-many relationship with the same model in rails?

您可以通过更改Location#exits关系的名称来获取Location#locations而不是has_many

class Location < ActiveRecord::Base
  # has_many :locations   Instead of this...
  has_many :exits, :class_name => 'Location' # ...Do this
  validates :name, presence: true, length: { minimum: 1 }
  validates :description, presence: true
end

这称为自联接。您将模型与自身相关联。

请注意,这会使Location#locations无效。

然后在您的表单中,您将执行以下操作:

<% @locations.each do |e| %>
  <%= f.label :exit %>
  <%= f.check_box :exit %>
<% end %>

Ruby on Rails网站提供了一个关于关联的很好的指南,包括像您一样要问的自联接:http://guides.rubyonrails.org/association_basics.html#self-joins

如果你喜欢RailsCasts:http://railscasts.com/episodes/163-self-referential-association