小编yer*_*syl的帖子

如何使用React和Rails创建表单?

使用Rails,我使用form_for标记创建表单.

Rails自动生成HTML表单,包括authenticity_token,以防止跨站点请求伪造(CSRF).

使用React我使用JSX,因此我无法在React组件中呈现erb.

在React组件中,我手动编写HTML.

我想在我的Rails应用程序中使用React,并且仍然具有Rails的优点.

或者,如果在使用React作为我的应用程序的V时无法获得form_for的Rails优势,我该如何编写一个适当的表单作为React组件?

如果我首先编写我的form_for,然后查看渲染的HTML,复制它,并粘贴到我的React组件中,这是一个好主意吗?

例如,这里是form_for呈现的HTML:

<form class="new_user" id="new_user" action="/users" accept-charset="UTF-8" method="post">
  <input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="1AXH9blzaH4qEAAWTvu6aAH84btA/9DZCpFDBhiJ0/H9uAKsPAB/rFQWY1VmWA1yNtFaigO50p6joa3X8CItBA==" />
  

  <div class="field">
    <label for="user_???">???</label><br>
    <input placeholder="??? ?????" type="text" name="user[name]" id="user_name" />
  </div>


  <div class="actions">
    <input type="submit" name="commit" value="??????? ??????" class="button tiny" />
  </div>

</form>
Run Code Online (Sandbox Code Playgroud)

html ruby-on-rails reactjs

33
推荐指数
3
解决办法
1万
查看次数

Devise SessionsController:create 的未定义方法“user_url”

我有使用 devise gem 进行授权的用户模型。我想添加 after_sign_in_path 方法:

# application_controller.rb

protected
# redirecting to appropriate url based on role
  def after_sign_in_path_for(resource)
    if current_user.has_role?(:admin)
      dashboard_path
    elsif current_user.has_role?(:student)
      root_path
    end
  end
Run Code Online (Sandbox Code Playgroud)
每当我尝试登录时,都会收到此错误:

undefined method `user_url' for #<Devise::SessionsController:0x007fb89b5b00a8> Did you mean? course_url
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它会说“你是说吗?” course_url。但我有课程模型。这是我的路线:

authenticate :user do

    resources :feeds, only: [:index]
    resources :courses, only: [:index, :show]    
    # etc...

  end
Run Code Online (Sandbox Code Playgroud)

这也是它指向我的代码:

if options.empty?
            recipient.send(method, *args)
  else
            recipient.send(method, *args, options)
  end
Run Code Online (Sandbox Code Playgroud)

和日志的第一行:

actionpack (4.2.4) lib/action_dispatch/routing/polymorphic_routes.rb:220:in `polymorphic_method' 
Run Code Online (Sandbox Code Playgroud)

每当我推荐 after_sign_in_path_for 时,我都可以登录。如果我评论 after_sign_in_path_for 的内容但保留空 after_sign_in_path_for 方法,我也会收到此错误。

编辑:我测试过我还没有登录,而不仅仅是没有重定向。我认为错误发生在调用 after_sign_in_path_for 中,而不是在 redirect_to …

ruby-on-rails devise ruby-on-rails-4

16
推荐指数
3
解决办法
2万
查看次数

检查用户是否在Rails中的任何操作之前登录

我想在任何控制器操作之前执行一些函数来检查用户是否已登录.我正在使用设计以便我可以使用is_signed_in ?,但我必须将if else条件放入控制器中的每个方法.

我想要的是这样的东西:

#some_controller.rb
before_action :is_signed_in?

def is_signed_in?
   if !user_signed_in?
      redirect_to new_user_session_path
   else 
      ..proceed to the action intended to call
   end
end
Run Code Online (Sandbox Code Playgroud)
因此,我希望此方法在任何操作(或一组操作)之前执行,并重定向以登录为false,或者让该操作执行如果为true.

ruby-on-rails ruby-on-rails-4

10
推荐指数
2
解决办法
2万
查看次数

_destroy在使用Rails 4的Coocon gem中无效

我有同样的问题,因为这 一个

但那个解决方案对我没有帮助.这是我强大的参数:

def request_params
   params.require(:request).permit(:name, :address, :phone, :mobile, :type,
     :filled_cartridges_attributes => [:cartridge_name,:client_id,,
				:count,:_destroy,:id],							
Run Code Online (Sandbox Code Playgroud)

所以我有:_destroy和:id.之前的家伙忘记添加:id to strong params.添加id解决了他的问题.

这是我的请求模型:

has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
	accepts_nested_attributes_for :filled_cartridges, :reject_if => :all_blank, allow_destroy: true
Run Code Online (Sandbox Code Playgroud)

这就是提交后params的样子:

request: 
...some params....
filled_cartridges_attributes: !ruby/hash:ActionController::Parameters
    '0': !ruby/hash:ActionController::Parameters
      cartridge_name: HP LaserJet3000
      _destroy: 'false'
      id: '1'
    '2': !ruby/hash:ActionController::Parameters
     cartridge_name: new 9
     _destroy: '1'
     id: '13'
Run Code Online (Sandbox Code Playgroud)

这里应该销毁第二个.但事实并非如此.

ruby ruby-on-rails ruby-on-rails-4 cocoon-gem

7
推荐指数
1
解决办法
413
查看次数

如果我将 MongoDB 与 Rails 结合使用,我可以使用 Active Record 关联吗?

我计划使用 mongoDb 构建 Rails 应用程序,但我不知道我是否能够使用活动记录关联(例如多对多等)?另外,当我将 mongoDb 与 Rails 一起使用时,我是否将 Active Record ORM 替换为 mongoDB 的其他 ORM。抱歉,如果问题很愚蠢,我只是从未将 mongoDB (noSql) 与 Rails 一起使用。

ruby-on-rails mongodb ruby-on-rails-4

7
推荐指数
1
解决办法
5447
查看次数

通过Rails 4中的image_tag在生产中未提供的图像

我将我的应用程序部署到生产环境中,发现图像不是从image_tag提供的,而是在我使用asset_path时提供的.我在app/assets/images下有我的图像.在生产中,我预先编译它们,使它们处于公共/资产中,并具有诸如"image_name-fk3r23039423-0e9232.png"之类的名称.

当我查看生成的html代码时,我看到我的image_tag的src是

/images/logo
Run Code Online (Sandbox Code Playgroud)

而asset_path生成这个:

/assets/login-bg1-01eead5b47afcb7e0a951a3668ec3921e8df3f4507f70599f1b84d5efc971855.jpg
Run Code Online (Sandbox Code Playgroud)

所以这是正确的.所以我很感兴趣为什么我不能使用image_tag'image-name'来提供图片?

这是我的production.rb

config.serve_static_files = true

config.assets.compile = false

config.assets.digest = true
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails ruby-on-rails-4 digital-ocean

7
推荐指数
1
解决办法
1129
查看次数

冒泡在C中使用指针的结构

我想使用冒泡排序算法和C中的指针对结构数组进行排序.我有一个汽车结构:

typedef struct{
    char model[30];
    int hp;
    int price;
}cars;
Run Code Online (Sandbox Code Playgroud)

我为12个项目分配内存:

cars *pointer = (cars*)malloc(12*sizeof(cars));
Run Code Online (Sandbox Code Playgroud)

并从文件中读取数据:

for (i = 0; i <number ; i++) {
    fscanf(file, "%s %i %i\n", (pointer+i)->model, &(pointer+i)->hp, &(pointer+i)->price);
}
Run Code Online (Sandbox Code Playgroud)

我将指针传递ptrbubbleSort函数:

bubbleSort(pointer, number);
Run Code Online (Sandbox Code Playgroud)

这是我的bubbleSort功能:

void bubbleSort(cars *x, int size) {
    int i, j;
    for (i=0;i<size-1;i++) {
    int swapped = 0;
    for (j = 0; j < size - 1 - i; j++) {
        if ( (x+i)->hp > (x+j+1)->hp ) {
            cars …
Run Code Online (Sandbox Code Playgroud)

c struct pointers bubble-sort

6
推荐指数
1
解决办法
5150
查看次数

更改 Rails create 中的 PostgreSQL 默认 ID 序列

我有一个 sql 转储文件,已导入到我的数据库中。此 sql 转储中的所有记录的 id 都从 900 开始到 2500。

所以问题是,如果我从 Rails 应用程序创建新记录,它将自动获得 id = 1,下一个将获得 2,3,4 等。我想当我创建 900s 记录时,我会得到一个错误,因为 id=900 已经存在。

注意:我无法在 sql 转储文件中将我的 id 更改为从 1 开始,因为另一个表通过 id 引用它。

有什么解决办法吗?

我使用 PostgreSQL

postgresql ruby-on-rails

6
推荐指数
1
解决办法
1109
查看次数

无法读取null的属性'_currentElement'

我正在做react-rails app.我收到了这个奇怪的错误.似乎这是反应本身的问题.这是我收到此错误的上下文:

var ChronicBox = React.createClass({

    getInitialState: function(){
      return {chronics: []}
    },
    componentWillMount: function(){
      $.ajax({
     // some ajax call that setsState of chronicles
      });
    },
    render: function(){
        return(
            <div className="chronics">
                <ChronicsList chronics={this.state.chronics.chronicsList} />
            </div>
        )
    }
});
Run Code Online (Sandbox Code Playgroud)

和My ChronicsList看起来像:

var ChronicsList = React.createClass({
    render:function(){
        console.log(this.props.chronics);
        var chronics = this.props.chronics.map(function(chronic){
            return(
                <Chronic name={chronic.name}/>
            )
        });

        return(
            <ul>
                {chronics}
            </ul>
        )
    }
});
Run Code Online (Sandbox Code Playgroud)

从日志我看到这个:

undefined
can not read property .map of undefined
Cannot read property '_currentElement' of null
Run Code Online (Sandbox Code Playgroud)

从这些我看到最初状态的时间顺序为空,因此.map不能使用.然后当ajax调用setsState时,我的ChronicBox重新渲染,而chronics包含json信息,如下所示:

{
    "chronicsList": [{ …
Run Code Online (Sandbox Code Playgroud)

reactjs

6
推荐指数
1
解决办法
2万
查看次数

Flask:使用unittest进行测试 - 如何从响应中获取.post json

我正在用python3在烧瓶中进行单元测试.我有返回json的方法:

@app.route('/doctor/book_appointment', methods=['POST'])
def some_method():
  resp = {
          "status": "",
          "message": ""
        }
  return jsonify(resp)
Run Code Online (Sandbox Code Playgroud)

所以在我的单元测试中我试试这个:

headers = {
        'ContentType': 'application/json',
        'dataType': 'json'
}
data = {
    'key1': 'val1',
    'key2': 'val2'
}
response = self.test_app.post('/doctor/book_appointment',
                                      data=json.dumps(data),
                                      content_type='application/json',
                                      follow_redirects=True)
        self.assertEqual(response.status_code, 200)
# hot to get json from response here
# I tried this, but doesnt work
json_response = json.loads(resp.data)
Run Code Online (Sandbox Code Playgroud)

我的响应对象是Response流式.我如何从中获取json.由于some_method返回jsonified数据.BTW它可以在一些javascript框架消耗我的api时工作,即我可以从响应中获取json.但现在我需要在python中测试代码.

python flask python-unittest

6
推荐指数
1
解决办法
3751
查看次数