问题描述:

All, I have two dropdown boxes, which are populated from two different database tables and a form with a single submit button. My goal is to concatenate the two values upon form submit and write the single value back to the database into the form associated with the model.

More simply: two dropboxes allowing to select ['red','green','blue'] and ['dog','cat']. The user selects 'red' and 'cat', and the submit button creates a new record 'red-cat' (under the blogname model) as a result.

ENTIRE Form (new.html.erb) code:

<%= select("subdomainw1", "blognamew1", Subdomainw1.order("blognamew1 ASC").collect {|p| [ p.blognamew1 ] }, {:prompt => 'Select Adjective'}) %>

<%= select("subdomainw2", "blognamew2", Subdomainw2.order("blognamew2 ASC").collect {|p| [ p.blognamew2 ] }, {:prompt => 'Select Noun'}) %>

<%= simple_form_for (@blogname) do |f| %>

<%= f.button :submit %>

<% end %>

with the associated controller def create being:

 def create

@blogname = Blogname.new(params[:blogname])

respond_to do |format|

@blogname.blogname = ?? THIS SHOULD BE A CONCATENATION OF THE VALUES FROM ABOVE SELECTS

if @blogname.save

format.html { redirect_to @blogname, notice: 'Blog was successfully created.' }

else

format.html { render action: "new" }

end

end

end

Any ideas here?

网友答案:

There are a lot of ways to do this, the Rails way would be to do it in your model and keep your controllers skinny.

I think the most common way in rails you'll see this done is a callback. So, for this example you could set up a before_validation (or perhaps before_create if you don't want it to be changed if the blog is edited) call back in your mode, and assign your blogname from the two other attributes.

model.rb

before_validation :generate_blogname

def generate_blogname
   self.blogname ||= "#{blognamew1}-#{blognamew2}".parameterize
end

Then in your controller:

 controller.rb

 def create
    @blogname = Blogname.new(params[:blogname])

    respond_to do |format|
       if @blogname.save
        format.html { redirect_to @blogname, notice: 'Blog was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
 end

The parameterize method will make this work for subdomains by taking out special characters. The model shouldn't probably be called blogname, it should probably be a table blog with an attribute of name. So @blog = Blog.new, then @blog.name = "Two Subdomain Values"

相关阅读:
Top