开发者

ruby on rails - nested forms

I have a form that sets the attributes of a model, however, there is an attribute that I want to set through the code. That is, I want the user to set some attributes, but I want the program to set other attributes.

Is there any way of doing this?

Example:

If I have table with a "text" column and a "user" column, I want the user to enter the开发者_C百科 text, but I want the "user" column to be set by the program. How would I accomplish this?


Sure. You could do something like this:

 def create
   @something = Something.new(params[:something])
   @something.programmatically_set_attribute = "Some value"  #Here's the part that matters

   respond_to do |format|
     if @host.save
       format.html { redirect_to(@something, :notice => 'Something was successfully created.') }
       format.xml  { render :xml => @something, :status => :created, :location => @something}
     else
       format.html { render :action => "new" }
       format.xml  { render :xml => @something.errors, :status => :unprocessable_entity }
     end
   end
end

In your form, you would just leave out the field that you don't want edited by human hands. You would also have to change the update function, as well.


If you want to ensure that only the text attribute is updateable by the user and none other you may want to use attr_accessible as follows

class MyModel < ActiveRecord::Base
  attr_accesssible :text
end

This will ensure that only the text attribute of MyModel can be updated via mass-assignment.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜