I've been struggling with this far too long now.
For the simplicity, suppose I have Lead The Jungle app in which users ask for Recommendations to some destinations. In answer to this, other, experienced users propose a guide man who will lead them straight to the point.
Suppose I have the following models.
class User < ActiveRecord::Base
has_many :destinations
validates :username, :email
#..
end
class Recommendation < ActiveRecord::Base
belongs_to :user
belongs_to :destination
belongs_to :guide
#..
end
class Gu开发者_如何学JAVAide < ActiveRecord::Base
has_many :recommendations
validates :name, :nickname, :phone
#..
end
class Destination < ActiveRecord::Base
has_many :recommendations
has_many :users
#..
end
On my page, next to the map of the jungle I want to have single widget in which I can propose up to three recommendations with related guide man to a single destination. I also want to give contact details to the guide man.
The thing is, I don't have these three recommended guides under some grouping relation (such as photos under gallery). So I can't simply use nested attributes in this case.
Is there a way to create multiple nested objects without a single parent object containing them all?
I tried the following (among many other approaches) but guides parameter's aren't under theirs recommendations and I can't see which guide is connected to which recommendation.
<%= form_tag('recommendations') do -%>
<ul id="selected-guides">
<% @recommendations.each_with_index do |recommendation, index| %>
<%= render 'recommendation_fields', :recommendation => recommendation} %>
<% end %>
</ul>
<%= submit_tag %>
<% end %>
_recommendation_fields.erb
<%= fields_for recommendation do |Recommendation_fields| %>
<div>
<%= fields_for recommendation.guide do |guide_fields| %>
<%= guide_fields.text_field :name %>
<%= guide_fields.text_field :nickname %>
<%= guide_fields.text_field :phone %>
<% end %>
</div>
<% end %>
Thank you for your help!
you may try rails 3.1 and go with a has many through assosiaction. See the new screencast from ryan bates, it may helps you!
http://railscasts.com/episodes/265-rails-3-1-overview
ryans example for a Project (models/project.rb)
has_many :tasks
has_many :assigments, :through => :tasks
has_many :users, :through => :assignments
in your case, you can access also like this, I suppose
精彩评论