开发者

Select input element using f.select() of items connected by a linking table (in Rails)

I have a form for an instance of a "project". Each project can have many clients. Each client is a unique pair of organization and individual (contact person).

So, Project has a many-to-many relationship with Client. Client has a many-to-one relationship with organization and a many-to-one relationship with Organization.

See an image of the model diagram: http://dl.dropbox.com/u/631919/erm.png

In the edit page for a project, I'd like to be able to change the organization for each client through a drop down select menu, but I'm having trouble getting the organizations to appear in the select input item.

Here's what I have:

<% form_for(@p开发者_开发知识库roject) do |f| %>

  <% @project.clients.each do |client| %> 

    <%= f.select("client.organization_id", Disclosure.all.collect {|d| [d.color.titlecase, d.id] }) %>   

  <% end %>

<% end %>

I know this is wrong, but I don't know how you get a select drop-down menu that I want, which is a select menu with the organization associated with each client as the default selection.

Any help?


Your schema seems somewhat strange to me...but anyhow..

If you want to list all the organizations in the select and have the current one be defaulted try this:

<%= f.select("client.organization_id", Organization.all.collect {|o| [o.name, o.id] }) %>

The client.organization_id that is current should be selected if this is a restful edit action. See below.

From the docs: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M002302

Example with @post.person_id => 1:

 select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })

could become:

<select name="post[person_id]">
    <option value=""></option>
    <option value="1" selected="selected">David</option>
    <option value="2">Sam</option>
    <option value="3">Tobias</option>
  </select>


<% form_for(@project) do |f| %>

  <% @project.clients.each do |client| %> 
    <% fields_for :client, client do |c| %>
      <%= collection_select(client, :organization_id, ORganization.all, :id, :name) %>   
    <% end %>
  <% end %>

<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜