2

私はユーザーモデルを持っており、各ユーザーには会社名とそれに関連付けられた都市があります。このプロジェクトでは、都市に基づいて各ユーザーをリストする必要があります。例:citywise / san-francisco、citywise/new-york。現在、これらは念頭に置いているモデルです

class User < ActiveRecord::Base
  attr_accessible :name, :company

  belongs_to :city
end

class City < ActiveRecord::Base
  attr_accessible :name, :slug

  has_many :users
end

また、都市を事前定義されたリストにすることはできません。各ユーザーがDBに作成されるときに作成する必要があります。

では、ユーザーの作成/更新中に都市にアクセスまたは作成するにはどうすればよいですか?

4

2 に答える 2

1

First things first, you need to add accepts_nested_attributes_for and attributes_for :cities_attributes to your City model:

class City < ActiveRecord::Base
  attr_accessible :name, :slug, attributes_for :cities_attributes
  accepts_nested_attributes_for :cities

  has_many_users
end

Since you now have access to all the attributes within your City model, you can include these in your form using fields for.

<%= form_for@city do |f| %>
   # City attributes
  <%= f.fields_for :users do |c| %>
     # User attributes
  <% end %>
<% end %>

In your index view you could also use nesting:

<% @cities.each do |city| %>
  # city attributes goes here
  <% city.users.each do |user| %>
    # user attributes goes here 

The first line shows all the attributes for each city you have defined, whereas the second line shows the attributes for each user for a particular city.

于 2013-02-08T07:36:05.830 に答える
0

User モデルのネストされた属性を確認する必要があります。

accepts_nested_attributes_forこれは、あなたを助けるはずの方法のドキュメントです。http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

于 2013-02-08T06:58:27.793 に答える