开发者

Using Has_and_belongs_to_many association in multi model view rails

I am new to rails and having trouble with views so excuse me if this is a simple question. I was wondering how add to a has_and_belongs_to_many association in the view.

Here is the situation I have a model with the following mongoid documents:

class Project
  include Mongoid::Document
  field :name, type: String
  key :name
  field :numPeople, type: Integer
  has_and_belongs_to_many :people
end

and...

class Person
  include Mongoid::Document
  field :name, type: String
  key :name
  field :numProjects, type: Integer, default: 0
  has_and_belongs_to_many :projects
end

What I want is a Person page with the ability to write the name of a project in a text field and if the project exists it will add him to the project and if it doesn't exist it will create a new project with the name he specified.

What I want is similar to this (in HAML):

= form_for Project.new do |f|
    %p
        = f.text_field :name
        = f.submit "Add Project"

but I开发者_StackOverflow do not want to create a new project each time because the project may already exist.

I looked up stuff on formtastic and nested_form but did not see a perfect example that matched my scenario.

Thanks


I'm a noob, but i think i can help - not for the view part, but for the logic beneath.

It seems you will need an action in your PersonPagesController that will be called on form submission (admitting that your form sends a person_name and a project_name), that should look like :

def add_person_to_project
  @person = Person.find(params[:person_name])
  @project = Project.find_or_create_by_name(params[:project_name])
  @project.persons << @person # or @person.projects << @project
end

information on find_or_create can be found there http://api.rubyonrails.org/classes/ActiveRecord/Base.html (under "Dynamic Attribute-based Finders")

you will obviously have to send the person's name with the form for this to work, which you should be able to do by adding a pre-filled hidden field when generating the empty form for a specific person (i don't know formstatic and nested_form though...). You may also want to secure this a bit ( check if a person is really found, and if that person does not already belong to the project before adding it...)

Also, i would generally not advise to use the name fields as keys for your persons and projects, but that's up to you. I would advise, though, that you implement this another way, letting the user choose the project in a list or create a new one (what happens if your user makes a typo for example ?)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜