Rails 3 - best_in_place editing

我与影子孤独终老i 提交于 2019-12-05 05:47:20

The :collection parameter accepts an array of key/value pairs:

    [ [key, value], [key, value], [key, value], ... ]

Where the key is the option value and value is the option text.

It is best to generate this array in the model corresponding to the object for which you want to generate a list of options for, and not in your view.

Sounds like you have best_in_place up and running, so here's a simple example of a project show page, where you want to use best_in_place to change the assigned user for a particular project with a select box.

## CONTROLLER

# GET /projects/1
# GET /projects/1.xml
# GET /projects/1.json
def show
  @project = Project.find(params[:id])

  respond_to do |format|
    format.html
    format.xml  { render :xml => @project.to_xml }
    format.json { render :json => @project.as_json }
  end
end


## MODELS

class User
  has_many :projects

  def self.list_user_options 
    User.select("id, name").map {|x| [x.id, x.name] }
  end
end

class Project
  belongs_to :user
end


## VIEW (e.g. show.html.erb)
## excerpt

<p>
  <b>Assigned to:</b>
  <%= best_in_place @project, :user_id, :type => :select, :collection => User::list_user_options %>
</p>

# note :user_id and not :user

Note that from memory, the master version of best_in_place sends the ajax request for a select box whether the value is changed or not.

Also something to keep in mind; best_in_place is for "in place" editing of existing records, not creating new ones (for that, use collection_select in your _form partial for the new page).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!