从隐藏字段Ruby on Rails设置对象属性

时间:2015-06-18 20:00:28

标签: ruby-on-rails ruby forms ruby-on-rails-4

我正在尝试通过隐藏的表单字段更新Idea属性challenge_id。这是字段:

<%= f.hidden_field :challenge_id, :value => @challenge.id %>

当为Idea Controller #create方法创建一个想法时,它成功地将挑战ID作为参数传递:

Started POST "/ideas.js" for ::1 at 2015-06-18 15:39:49 -0400 Processing by IdeasController#create as JS Parameters: {"utf8"=>"✓", "idea"=>{"title"=>"adsf", "description"=>"asf", "domain_tokens"=>"20", "challenge_id"=>"5"}, "commit"=>"Create Idea"}

然后应将此challenge_id => 5保存到以下行@idea = Idea.new(idea_params)中的想法中:

ideas_controller.rb

def create
    @idea = Idea.new(idea_params)

    respond_to do |format|
      if @idea.save
        idea_count = @idea.user.ideas_created_count
        @idea.user.update(:ideas_created_count => idea_count + 1)
        @idea.domains.each do |domain|
          current_user.add_points(1, category: domain.title)
        end
        @ideas = current_user.current_team.ideas.sort_by{|i| i.heat_index}.reverse
        @ideas = @ideas.paginate(:page => params[:ideas_page], :per_page => 10)
        format.html { redirect_to :back, notice: 'Idea was successfully created.' }
        format.json { render :show, status: :created, location: @idea }
        format.js
      else
        format.html { redirect_to :back, notice: "You must attach domains to your Idea." }
        format.json { render json: @idea.errors, status: :unprocessable_entity }
        format.js { render :create_failed }
      end
    end
  end
  .
  .
  def idea_params
   params.require(:idea).permit(:title, :description, :challenge_id)
  end

但是,此挑战ID未保存到idea,其他允许的idea_params:title:description。如何在创建创意时将challenge_id保存到创意中?

2 个答案:

答案 0 :(得分:0)

我假设你在ideas表中有challenge_id列。

尝试类似:

def create
    @idea = Idea.new(idea_params)
    @idea.challenge_id = params[:idea][:challenge_id]
     #...
 end

如果你想要保存它的params或列是不同的,请确保进行更改,但你明白了。

答案 1 :(得分:0)

为什么不在表单中传入challenge_id,而不是使用隐藏字段?否则,您可以在用户可以在该隐藏字段中输入他们想要的任何内容。

形式:

form_for [@challenge, Idea.new] do |f|

然后:

def create
    @challenge = Challenge.find(params[:challenge_id])
    @idea = Idea.new(idea_params)
    @idea.challenge_id = @challenge.id
end